userver: userver/fs/fs_cache_client.hpp Source File
Loading...
Searching...
No Matches
fs_cache_client.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/fs/fs_cache_client.hpp
4/// @brief @copybrief fs::FsCacheClient
5
6#include <chrono>
7#include <cstddef>
8#include <string>
9#include <string_view>
10
11#include <userver/engine/io/sys_linux/inotify.hpp>
12#include <userver/engine/task/task_processor_fwd.hpp>
13#include <userver/fs/read.hpp>
14#include <userver/rcu/rcu_map.hpp>
15#include <userver/utils/impl/transparent_hash.hpp>
16#include <userver/utils/periodic_task.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace fs {
21
22namespace impl {
23
24struct FsCacheRcuMapTraits : public rcu::DefaultRcuMapTraits<std::string> {
25 using Hash = utils::impl::TransparentHash<std::string>;
26 using KeyEqual = std::equal_to<>;
27};
28
29} // namespace impl
30
31/// Default maximum file size stored in memory by FsCacheClient (1 GiB).
32inline constexpr std::size_t kDefaultMaxSizeToCache = 1024ULL * 1024 * 1024;
33
34/// @ingroup userver_clients
35///
36/// @brief Class client for storing files in memory
37/// Usually retrieved from `components::FsCache`
38class FsCacheClient final {
39public:
40 /// Configuration parameters for FsCacheClient.
41 struct Settings final {
42 /// Directory to cache files from
43 std::string dir;
44
45 /// Update period (0 - fill the cache only at startup), not used in Linux
46 std::chrono::milliseconds update_period{0};
47
48 /// Task processor to do filesystem operations
49 engine::TaskProcessor& task_processor;
50
51 /// For files larger than this limit, the full path is stored instead of the contents
53 };
54
55 /// @brief Fills the cache and starts periodic update
56 explicit FsCacheClient(const Settings& settings);
57
58 /// @brief get file from memory
59 /// @param path to file
60 /// @return file info and content ; `nullptr` if no file with specified name
61 /// on FS
62 FileInfoWithDataConstPtr TryGetFile(std::string_view path) const;
63
64 /// @brief Concurrency-safe cache update
66
67private:
68#ifdef __linux__
69 void InotifyWork();
70
71 void HandleDelete(const std::string& path);
72
73 static void HandleDeleteDirectory(engine::io::sys_linux::Inotify& inotify, const std::string& path);
74
75 void HandleCreate(const std::string& path);
76
77 void HandleCreateDirectory(engine::io::sys_linux::Inotify& inotify, const std::string& path);
78
79 void HandleCreateDirectoryBlocking(engine::io::sys_linux::Inotify& inotify, const std::string& path);
80#endif
81
82 const std::string dir_;
83 const std::chrono::milliseconds update_period_;
84 const std::size_t max_size_to_cache_;
85 engine::TaskProcessor& tp_;
86#ifndef __linux__
87 utils::PeriodicTask cache_updater_;
88#endif
89 rcu::RcuMap<std::string, const fs::FileInfoWithData, impl::FsCacheRcuMapTraits> data_;
90
91#ifdef __linux__
92 engine::Task inotify_task_;
93#endif
94};
95
96} // namespace fs
97
98USERVER_NAMESPACE_END