Coverage Report

Created: 2026-03-21 13:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/block_file_cache.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#pragma once
19
20
#include <bvar/bvar.h>
21
#include <concurrentqueue.h>
22
23
#include <algorithm>
24
#include <array>
25
#include <atomic>
26
#include <boost/lockfree/spsc_queue.hpp>
27
#include <functional>
28
#include <memory>
29
#include <mutex>
30
#include <optional>
31
#include <thread>
32
#include <unordered_map>
33
#include <vector>
34
35
#include "io/cache/block_file_cache_ttl_mgr.h"
36
#include "io/cache/cache_lru_dumper.h"
37
#include "io/cache/file_block.h"
38
#include "io/cache/file_cache_common.h"
39
#include "io/cache/file_cache_storage.h"
40
#include "io/cache/lru_queue_recorder.h"
41
#include "runtime/runtime_profile.h"
42
#include "util/threadpool.h"
43
44
namespace doris::io {
45
using RecycleFileCacheKeys = moodycamel::ConcurrentQueue<FileCacheKey>;
46
47
class LockScopedTimer {
48
public:
49
5.33k
    LockScopedTimer() : start_(std::chrono::steady_clock::now()) {}
50
5.33k
    ~LockScopedTimer() {
51
5.33k
        auto end = std::chrono::steady_clock::now();
52
5.33k
        auto duration_us =
53
5.33k
                std::chrono::duration_cast<std::chrono::microseconds>(end - start_).count();
54
5.33k
        if (duration_us > config::cache_lock_held_long_tail_threshold_us) {
55
0
            LOG(WARNING) << "Lock held time " << std::to_string(duration_us) << "us. "
56
0
                         << get_stack_trace();
57
0
        }
58
5.33k
    }
59
60
private:
61
    std::chrono::time_point<std::chrono::steady_clock> start_;
62
};
63
64
// Note: the cache_lock is scoped, so do not add do...while(0) here.
65
#define SCOPED_CACHE_LOCK(MUTEX, cache)                                                           \
66
5.31k
    std::chrono::time_point<std::chrono::steady_clock> start_time =                               \
67
5.31k
            std::chrono::steady_clock::now();                                                     \
68
5.31k
    std::lock_guard cache_lock(MUTEX);                                                            \
69
5.31k
    std::chrono::time_point<std::chrono::steady_clock> acq_time =                                 \
70
5.31k
            std::chrono::steady_clock::now();                                                     \
71
5.31k
    auto duration_us =                                                                            \
72
5.31k
            std::chrono::duration_cast<std::chrono::microseconds>(acq_time - start_time).count(); \
73
5.31k
    *(cache->_cache_lock_wait_time_us) << duration_us;                                            \
74
5.31k
    if (duration_us > config::cache_lock_wait_long_tail_threshold_us) {                           \
75
0
        LOG(WARNING) << "Lock wait time " << std::to_string(duration_us) << "us. "                \
76
0
                     << get_stack_trace() << std::endl;                                           \
77
0
    }                                                                                             \
78
5.31k
    LockScopedTimer cache_lock_timer;
79
80
class FSFileCacheStorage;
81
82
// NeedUpdateLRUBlocks keeps FileBlockSPtr entries that require LRU updates in a
83
// deduplicated, sharded container. Entries are keyed by the raw FileBlock
84
// pointer so that multiple shared_ptr copies of the same block are treated as a
85
// single pending update. The structure is thread-safe and optimized for high
86
// contention insert/drain workloads in the background update thread.
87
// Note that Blocks are updated in batch, internal order is not important.
88
class NeedUpdateLRUBlocks {
89
public:
90
166
    NeedUpdateLRUBlocks() = default;
91
92
    // Insert a block into the pending set. Returns true only when the block
93
    // was not already queued. Null inputs are ignored.
94
    bool insert(FileBlockSPtr block);
95
96
    // Drain up to `limit` unique blocks into `output`. The method returns how
97
    // many blocks were actually drained and shrinks the internal size
98
    // accordingly.
99
    size_t drain(size_t limit, std::vector<FileBlockSPtr>* output);
100
101
    // Remove every pending block from the structure and reset the size.
102
    void clear();
103
104
    // Thread-safe approximate size of queued unique blocks.
105
10.4k
    size_t size() const { return _size.load(std::memory_order_relaxed); }
106
107
private:
108
    static constexpr size_t kShardCount = 64;
109
    static constexpr size_t kShardMask = kShardCount - 1;
110
111
    struct Shard {
112
        std::mutex mutex;
113
        std::unordered_map<FileBlock*, FileBlockSPtr> entries;
114
    };
115
116
    size_t shard_index(FileBlock* ptr) const;
117
118
    std::array<Shard, kShardCount> _shards;
119
    std::atomic<size_t> _size {0};
120
};
121
122
// The BlockFileCache is responsible for the management of the blocks
123
// The current strategies are lru and ttl.
124
125
struct FileBlockCell {
126
    friend class FileBlock;
127
128
    FileBlockSPtr file_block;
129
    /// Iterator is put here on first reservation attempt, if successful.
130
    std::optional<LRUQueue::Iterator> queue_iterator;
131
132
    mutable int64_t atime {0};
133
13.4k
    void update_atime() const {
134
13.4k
        atime = std::chrono::duration_cast<std::chrono::seconds>(
135
13.4k
                        std::chrono::steady_clock::now().time_since_epoch())
136
13.4k
                        .count();
137
13.4k
    }
138
139
    /// Pointer to file block is always hold by the cache itself.
140
    /// Apart from pointer in cache, it can be hold by cache users, when they call
141
    /// getorSet(), but cache users always hold it via FileBlocksHolder.
142
600k
    bool releasable() const {
143
600k
        return (file_block.use_count() == 1 ||
144
600k
                (file_block.use_count() == 2 && file_block->_owned_by_cached_reader));
145
600k
    }
146
147
617k
    size_t size() const { return file_block->_block_range.size(); }
148
149
70
    FileBlockCell() = default;
150
    FileBlockCell(FileBlockSPtr file_block, std::lock_guard<std::mutex>& cache_lock);
151
    FileBlockCell(FileBlockCell&& other) noexcept
152
16.9k
            : file_block(std::move(other.file_block)),
153
16.9k
              queue_iterator(other.queue_iterator),
154
16.9k
              atime(other.atime) {
155
16.9k
        file_block->cell = this;
156
16.9k
    }
157
158
    FileBlockCell& operator=(const FileBlockCell&) = delete;
159
    FileBlockCell(const FileBlockCell&) = delete;
160
161
0
    size_t dowloading_size() const { return file_block->_downloaded_size; }
162
};
163
164
class BlockFileCache {
165
    friend class FSFileCacheStorage;
166
    friend class MemFileCacheStorage;
167
    friend class FileBlock;
168
    friend struct FileBlocksHolder;
169
    friend class CacheLRUDumper;
170
    friend class LRUQueueRecorder;
171
    friend struct FileBlockCell;
172
173
public:
174
    // hash the file_name to uint128
175
    static UInt128Wrapper hash(const std::string& path);
176
177
    BlockFileCache(const std::string& cache_base_path, const FileCacheSettings& cache_settings);
178
179
161
    virtual ~BlockFileCache() {
180
161
        {
181
161
            std::lock_guard lock(_close_mtx);
182
161
            _close = true;
183
161
        }
184
161
        _close_cv.notify_all();
185
161
        if (_cache_background_monitor_thread.joinable()) {
186
140
            _cache_background_monitor_thread.join();
187
140
        }
188
161
        if (_cache_background_gc_thread.joinable()) {
189
140
            _cache_background_gc_thread.join();
190
140
        }
191
161
        if (_cache_background_evict_in_advance_thread.joinable()) {
192
140
            _cache_background_evict_in_advance_thread.join();
193
140
        }
194
161
        if (_cache_background_lru_dump_thread.joinable()) {
195
140
            _cache_background_lru_dump_thread.join();
196
140
        }
197
161
        if (_cache_background_lru_log_replay_thread.joinable()) {
198
140
            _cache_background_lru_log_replay_thread.join();
199
140
        }
200
161
        if (_cache_background_block_lru_update_thread.joinable()) {
201
140
            _cache_background_block_lru_update_thread.join();
202
140
        }
203
161
        if (_ttl_mgr) {
204
124
            _ttl_mgr.reset();
205
124
        }
206
161
    }
207
208
    /// Restore cache from local filesystem.
209
    Status initialize();
210
211
    /// Cache capacity in bytes.
212
14
    [[nodiscard]] size_t capacity() const { return _capacity; }
213
214
    // try to release all releasable block
215
    // it maybe hang the io/system
216
    size_t try_release();
217
218
140
    [[nodiscard]] const std::string& get_base_path() const { return _cache_base_path; }
219
220
    // Get storage for inspection
221
0
    FileCacheStorage* get_storage() const { return _storage.get(); }
222
223
    /**
224
         * Given an `offset` and `size` representing [offset, offset + size) bytes interval,
225
         * return list of cached non-overlapping non-empty
226
         * file blocks `[block1, ..., blockN]` which intersect with given interval.
227
         *
228
         * blocks in returned list are ordered in ascending order and represent a full contiguous
229
         * interval (no holes). Each block in returned list has state: DOWNLOADED, DOWNLOADING or EMPTY.
230
         *
231
         * As long as pointers to returned file blocks are hold
232
         * it is guaranteed that these file blocks are not removed from cache.
233
         */
234
    FileBlocksHolder get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
235
                                CacheContext& context);
236
237
    /**
238
     * record blocks read directly by CachedRemoteFileReader
239
     */
240
    void add_need_update_lru_block(FileBlockSPtr block);
241
242
    /**
243
     * Clear all cached data for this cache instance async
244
     *
245
     * @returns summary message
246
     */
247
    std::string clear_file_cache_async();
248
    std::string clear_file_cache_directly();
249
250
    /**
251
     * Reset the cache capacity. If the new_capacity is smaller than _capacity, the redundant data will be remove async.
252
     *
253
     * @returns summary message
254
     */
255
    std::string reset_capacity(size_t new_capacity);
256
257
    std::map<size_t, FileBlockSPtr> get_blocks_by_key(const UInt128Wrapper& hash);
258
259
    /// For debug and UT
260
    std::string dump_structure(const UInt128Wrapper& hash);
261
    std::string dump_single_cache_type(const UInt128Wrapper& hash, size_t offset);
262
263
    void dump_lru_queues(bool force);
264
265
    [[nodiscard]] size_t get_used_cache_size(FileCacheType type) const;
266
267
    [[nodiscard]] size_t get_file_blocks_num(FileCacheType type) const;
268
269
    // change the block cache type
270
    void change_cache_type(const UInt128Wrapper& hash, size_t offset, FileCacheType new_type,
271
                           std::lock_guard<std::mutex>& cache_lock);
272
273
    // remove all blocks that belong to the key
274
    void remove_if_cached(const UInt128Wrapper& key);
275
    void remove_if_cached_async(const UInt128Wrapper& key);
276
277
    // Shrink the block size. old_size is always larged than new_size.
278
    void reset_range(const UInt128Wrapper&, size_t offset, size_t old_size, size_t new_size,
279
                     std::lock_guard<std::mutex>& cache_lock);
280
281
    // get the hotest blocks message by key
282
    // The tuple is composed of <offset, size, cache_type, expiration_time>
283
    [[nodiscard]] std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>>
284
    get_hot_blocks_meta(const UInt128Wrapper& hash) const;
285
286
491
    [[nodiscard]] bool get_async_open_success() const { return _async_open_done; }
287
288
    BlockFileCache& operator=(const BlockFileCache&) = delete;
289
    BlockFileCache(const BlockFileCache&) = delete;
290
291
    // try to reserve the new space for the new block if the cache is full
292
    bool try_reserve(const UInt128Wrapper& hash, const CacheContext& context, size_t offset,
293
                     size_t size, std::lock_guard<std::mutex>& cache_lock);
294
295
    /**
296
     * Proactively evict cache blocks to free up space before cache is full.
297
     * 
298
     * This function attempts to evict blocks from both NORMAL and TTL queues to maintain 
299
     * cache size below high watermark. Unlike try_reserve() which blocks until space is freed,
300
     * this function initiates asynchronous eviction in background.
301
     * 
302
     * @param size Number of bytes to try to evict
303
     * @param cache_lock Lock that must be held while accessing cache data structures
304
     * 
305
     * @pre Caller must hold cache_lock
306
     * @pre _need_evict_cache_in_advance must be true
307
     * @pre _recycle_keys queue must have capacity for evicted blocks
308
     */
309
    void try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock);
310
311
    void update_ttl_atime(const UInt128Wrapper& hash);
312
313
    void pause_ttl_manager();
314
    void resume_ttl_manager();
315
316
    std::map<std::string, double> get_stats();
317
318
    // for be UTs
319
    std::map<std::string, double> get_stats_unsafe();
320
321
    using AccessRecord =
322
            std::unordered_map<AccessKeyAndOffset, LRUQueue::Iterator, KeyAndOffsetHash>;
323
324
    /// Used to track and control the cache access of each query.
325
    /// Through it, we can realize the processing of different queries by the cache layer.
326
    struct QueryFileCacheContext {
327
        LRUQueue lru_queue;
328
        AccessRecord records;
329
330
5
        QueryFileCacheContext(size_t max_cache_size) : lru_queue(max_cache_size, 0, 0) {}
331
332
        void remove(const UInt128Wrapper& hash, size_t offset,
333
                    std::lock_guard<std::mutex>& cache_lock);
334
335
        void reserve(const UInt128Wrapper& hash, size_t offset, size_t size,
336
                     std::lock_guard<std::mutex>& cache_lock);
337
338
69
        size_t get_max_cache_size() const { return lru_queue.get_max_size(); }
339
340
48
        size_t get_cache_size(std::lock_guard<std::mutex>& cache_lock) const {
341
48
            return lru_queue.get_capacity(cache_lock);
342
48
        }
343
344
50
        LRUQueue& queue() { return lru_queue; }
345
    };
346
347
    using QueryFileCacheContextPtr = std::shared_ptr<QueryFileCacheContext>;
348
    using QueryFileCacheContextMap = std::unordered_map<TUniqueId, QueryFileCacheContextPtr>;
349
350
    QueryFileCacheContextPtr get_query_context(const TUniqueId& query_id,
351
                                               std::lock_guard<std::mutex>&);
352
353
    void remove_query_context(const TUniqueId& query_id);
354
355
    QueryFileCacheContextPtr get_or_set_query_context(const TUniqueId& query_id,
356
                                                      std::lock_guard<std::mutex>& cache_lock,
357
                                                      int file_cache_query_limit_percent);
358
359
    /// Save a query context information, and adopt different cache policies
360
    /// for different queries through the context cache layer.
361
    struct QueryFileCacheContextHolder {
362
        QueryFileCacheContextHolder(const TUniqueId& query_id, BlockFileCache* mgr,
363
                                    QueryFileCacheContextPtr context)
364
7
                : query_id(query_id), mgr(mgr), context(context) {}
365
366
        QueryFileCacheContextHolder& operator=(const QueryFileCacheContextHolder&) = delete;
367
        QueryFileCacheContextHolder(const QueryFileCacheContextHolder&) = delete;
368
369
7
        ~QueryFileCacheContextHolder() {
370
            /// If only the query_map and the current holder hold the context_query,
371
            /// the query has been completed and the query_context is released.
372
7
            if (context) {
373
6
                context.reset();
374
6
                mgr->remove_query_context(query_id);
375
6
            }
376
7
        }
377
378
        const TUniqueId& query_id;
379
        BlockFileCache* mgr = nullptr;
380
        QueryFileCacheContextPtr context;
381
    };
382
    using QueryFileCacheContextHolderPtr = std::unique_ptr<QueryFileCacheContextHolder>;
383
    QueryFileCacheContextHolderPtr get_query_context_holder(const TUniqueId& query_id,
384
                                                            int file_cache_query_limit_percent);
385
386
0
    int64_t approximate_available_cache_size() const {
387
0
        return std::max<int64_t>(
388
0
                _cache_capacity_metrics->get_value() - _cur_cache_size_metrics->get_value(), 0);
389
0
    }
390
391
    Status report_file_cache_inconsistency(std::vector<std::string>& results);
392
    Status check_file_cache_consistency(InconsistencyContext& inconsistency_context);
393
394
private:
395
    LRUQueue& get_queue(FileCacheType type);
396
    const LRUQueue& get_queue(FileCacheType type) const;
397
398
    template <class T, class U>
399
        requires IsXLock<T> && IsXLock<U>
400
    void remove(FileBlockSPtr file_block, T& cache_lock, U& segment_lock, bool sync = true);
401
402
    FileBlocks get_impl(const UInt128Wrapper& hash, const CacheContext& context,
403
                        const FileBlock::Range& range, std::lock_guard<std::mutex>& cache_lock);
404
405
    template <class T>
406
        requires IsXLock<T>
407
    FileBlockCell* get_cell(const UInt128Wrapper& hash, size_t offset, T& cache_lock);
408
409
    virtual FileBlockCell* add_cell(const UInt128Wrapper& hash, const CacheContext& context,
410
                                    size_t offset, size_t size, FileBlock::State state,
411
                                    std::lock_guard<std::mutex>& cache_lock);
412
413
    Status initialize_unlocked(std::lock_guard<std::mutex>& cache_lock);
414
415
    void update_block_lru(FileBlockSPtr block, std::lock_guard<std::mutex>& cache_lock);
416
417
    void use_cell(const FileBlockCell& cell, FileBlocks* result, bool not_need_move,
418
                  std::lock_guard<std::mutex>& cache_lock);
419
420
    bool try_reserve_for_lru(const UInt128Wrapper& hash, QueryFileCacheContextPtr query_context,
421
                             const CacheContext& context, size_t offset, size_t size,
422
                             std::lock_guard<std::mutex>& cache_lock,
423
                             bool evict_in_advance = false);
424
425
    bool try_reserve_during_async_load(size_t size, std::lock_guard<std::mutex>& cache_lock);
426
427
    std::vector<FileCacheType> get_other_cache_type(FileCacheType cur_cache_type);
428
    std::vector<FileCacheType> get_other_cache_type_without_ttl(FileCacheType cur_cache_type);
429
430
    bool try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t offset, int64_t cur_time,
431
                                      std::lock_guard<std::mutex>& cache_lock,
432
                                      bool evict_in_advance = false);
433
434
    size_t get_available_cache_size(FileCacheType cache_type) const;
435
436
    FileBlocks split_range_into_cells(const UInt128Wrapper& hash, const CacheContext& context,
437
                                      size_t offset, size_t size, FileBlock::State state,
438
                                      std::lock_guard<std::mutex>& cache_lock);
439
440
    std::string dump_structure_unlocked(const UInt128Wrapper& hash,
441
                                        std::lock_guard<std::mutex>& cache_lock);
442
443
    std::string dump_single_cache_type_unlocked(const UInt128Wrapper& hash, size_t offset,
444
                                                std::lock_guard<std::mutex>& cache_lock);
445
446
    void fill_holes_with_empty_file_blocks(FileBlocks& file_blocks, const UInt128Wrapper& hash,
447
                                           const CacheContext& context,
448
                                           const FileBlock::Range& range,
449
                                           std::lock_guard<std::mutex>& cache_lock);
450
451
    size_t get_used_cache_size_unlocked(FileCacheType type,
452
                                        std::lock_guard<std::mutex>& cache_lock) const;
453
454
    void check_disk_resource_limit();
455
    void check_need_evict_cache_in_advance();
456
457
    size_t get_available_cache_size_unlocked(FileCacheType type,
458
                                             std::lock_guard<std::mutex>& cache_lock) const;
459
460
    size_t get_file_blocks_num_unlocked(FileCacheType type,
461
                                        std::lock_guard<std::mutex>& cache_lock) const;
462
463
    bool need_to_move(FileCacheType cell_type, FileCacheType query_type) const;
464
465
    void run_background_monitor();
466
    void run_background_gc();
467
    void run_background_lru_log_replay();
468
    void run_background_lru_dump();
469
    void restore_lru_queues_from_disk(std::lock_guard<std::mutex>& cache_lock);
470
    void run_background_evict_in_advance();
471
    void run_background_block_lru_update();
472
473
    bool try_reserve_from_other_queue_by_time_interval(FileCacheType cur_type,
474
                                                       std::vector<FileCacheType> other_cache_types,
475
                                                       size_t size, int64_t cur_time,
476
                                                       std::lock_guard<std::mutex>& cache_lock,
477
                                                       bool evict_in_advance);
478
479
    bool try_reserve_from_other_queue_by_size(FileCacheType cur_type,
480
                                              std::vector<FileCacheType> other_cache_types,
481
                                              size_t size, std::lock_guard<std::mutex>& cache_lock,
482
                                              bool evict_in_advance);
483
484
    bool is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
485
                     bool evict_in_advance) const;
486
487
    void remove_file_blocks(std::vector<FileBlockCell*>&, std::lock_guard<std::mutex>&, bool sync,
488
                            std::string& reason);
489
490
    void find_evict_candidates(LRUQueue& queue, size_t size, size_t cur_cache_size,
491
                               size_t& removed_size, std::vector<FileBlockCell*>& to_evict,
492
                               std::lock_guard<std::mutex>& cache_lock, size_t& cur_removed_size,
493
                               bool evict_in_advance);
494
495
    Status check_ofstream_status(std::ofstream& out, std::string& filename);
496
    Status dump_one_lru_entry(std::ofstream& out, std::string& filename, const UInt128Wrapper& hash,
497
                              size_t offset, size_t size);
498
    Status finalize_dump(std::ofstream& out, size_t entry_num, std::string& tmp_filename,
499
                         std::string& final_filename, size_t& file_size);
500
    Status check_ifstream_status(std::ifstream& in, std::string& filename);
501
    Status parse_dump_footer(std::ifstream& in, std::string& filename, size_t& entry_num);
502
    Status parse_one_lru_entry(std::ifstream& in, std::string& filename, UInt128Wrapper& hash,
503
                               size_t& offset, size_t& size);
504
    void remove_lru_dump_files();
505
506
    void clear_need_update_lru_blocks();
507
508
    // info
509
    std::string _cache_base_path;
510
    size_t _capacity = 0;
511
    size_t _max_file_block_size = 0;
512
513
    mutable std::mutex _mutex;
514
    bool _close {false};
515
    std::mutex _close_mtx;
516
    std::condition_variable _close_cv;
517
    std::thread _cache_background_monitor_thread;
518
    std::thread _cache_background_gc_thread;
519
    std::thread _cache_background_evict_in_advance_thread;
520
    std::thread _cache_background_lru_dump_thread;
521
    std::thread _cache_background_lru_log_replay_thread;
522
    std::thread _cache_background_block_lru_update_thread;
523
    std::atomic_bool _async_open_done {false};
524
    // disk space or inode is less than the specified value
525
    bool _disk_resource_limit_mode {false};
526
    bool _need_evict_cache_in_advance {false};
527
    bool _is_initialized {false};
528
529
    // strategy
530
    using FileBlocksByOffset = std::map<size_t, FileBlockCell>;
531
    using CachedFiles = std::unordered_map<UInt128Wrapper, FileBlocksByOffset, KeyHash>;
532
    CachedFiles _files;
533
    QueryFileCacheContextMap _query_map;
534
    size_t _cur_cache_size = 0;
535
    size_t _cur_ttl_size = 0;
536
    std::multimap<uint64_t, UInt128Wrapper> _time_to_key;
537
    std::unordered_map<UInt128Wrapper, uint64_t, KeyHash> _key_to_time;
538
    // The three queues are level queue.
539
    // It means as level1/level2/level3 queue.
540
    // but the level2 is maximum.
541
    // If some datas are importance, we can cache it into index queue
542
    // If some datas are just use once, we can cache it into disposable queue
543
    // The size proportion is [1:17:2].
544
    LRUQueue _index_queue;
545
    LRUQueue _normal_queue;
546
    LRUQueue _disposable_queue;
547
    LRUQueue _ttl_queue;
548
549
    // keys for async remove
550
    RecycleFileCacheKeys _recycle_keys;
551
552
    std::unique_ptr<LRUQueueRecorder> _lru_recorder;
553
    std::unique_ptr<CacheLRUDumper> _lru_dumper;
554
    std::unique_ptr<BlockFileCacheTtlMgr> _ttl_mgr;
555
556
    // metrics
557
    std::shared_ptr<bvar::Status<size_t>> _cache_capacity_metrics;
558
    std::shared_ptr<bvar::Status<size_t>> _cur_cache_size_metrics;
559
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_size_metrics;
560
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_cache_size_metrics;
561
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_element_count_metrics;
562
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_element_count_metrics;
563
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_cache_size_metrics;
564
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_element_count_metrics;
565
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_cache_size_metrics;
566
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_element_count_metrics;
567
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_cache_size_metrics;
568
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _queue_evict_size_metrics;
569
    std::shared_ptr<bvar::Adder<size_t>> _total_read_size_metrics;
570
    std::shared_ptr<bvar::Adder<size_t>> _total_hit_size_metrics;
571
    std::shared_ptr<bvar::Adder<size_t>> _total_evict_size_metrics;
572
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_bytes_metrics;
573
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_count_metrics;
574
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_time_metrics_matrix[4][4];
575
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_size_metrics_matrix[4][4];
576
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_self_lru_metrics_matrix[4];
577
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_try_release;
578
579
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_5m;
580
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_5m;
581
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_1h;
582
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_1h;
583
584
    std::shared_ptr<bvar::Adder<size_t>> _num_read_blocks;
585
    std::shared_ptr<bvar::Adder<size_t>> _num_hit_blocks;
586
    std::shared_ptr<bvar::Adder<size_t>> _num_removed_blocks;
587
588
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_read_blocks;
589
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_hit_blocks;
590
591
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_5m;
592
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_5m;
593
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_1h;
594
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_1h;
595
596
    std::shared_ptr<bvar::Status<double>> _hit_ratio;
597
    std::shared_ptr<bvar::Status<double>> _hit_ratio_5m;
598
    std::shared_ptr<bvar::Status<double>> _hit_ratio_1h;
599
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio;
600
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_5m;
601
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_1h;
602
    std::shared_ptr<bvar::Status<size_t>> _disk_limit_mode_metrics;
603
    std::shared_ptr<bvar::Status<size_t>> _need_evict_cache_in_advance_metrics;
604
    std::shared_ptr<bvar::Status<size_t>> _meta_store_write_queue_size_metrics;
605
606
    std::shared_ptr<bvar::LatencyRecorder> _cache_lock_wait_time_us;
607
    std::shared_ptr<bvar::LatencyRecorder> _get_or_set_latency_us;
608
    std::shared_ptr<bvar::LatencyRecorder> _storage_sync_remove_latency_us;
609
    std::shared_ptr<bvar::LatencyRecorder> _storage_retry_sync_remove_latency_us;
610
    std::shared_ptr<bvar::LatencyRecorder> _storage_async_remove_latency_us;
611
    std::shared_ptr<bvar::LatencyRecorder> _evict_in_advance_latency_us;
612
    std::shared_ptr<bvar::LatencyRecorder> _recycle_keys_length_recorder;
613
    std::shared_ptr<bvar::LatencyRecorder> _update_lru_blocks_latency_us;
614
    std::shared_ptr<bvar::LatencyRecorder> _need_update_lru_blocks_length_recorder;
615
    std::shared_ptr<bvar::LatencyRecorder> _ttl_gc_latency_us;
616
617
    std::shared_ptr<bvar::LatencyRecorder> _shadow_queue_levenshtein_distance;
618
    // keep _storage last so it will deconstruct first
619
    // otherwise, load_cache_info_into_memory might crash
620
    // coz it will use other members of BlockFileCache
621
    // so join this async load thread first
622
    std::unique_ptr<FileCacheStorage> _storage;
623
    std::shared_ptr<bvar::LatencyRecorder> _lru_dump_latency_us;
624
    std::mutex _dump_lru_queues_mtx;
625
    NeedUpdateLRUBlocks _need_update_lru_blocks;
626
};
627
628
} // namespace doris::io