Kagome
Polkadot Runtime Engine in C++17
module_cache.cpp
Go to the documentation of this file.
1 
7 
8 #include <fstream>
9 #include <vector>
10 
11 #include "crypto/hasher.hpp"
12 
13 namespace kagome::runtime::wavm {
14  ModuleCache::ModuleCache(std::shared_ptr<crypto::Hasher> hasher,
15  fs::path cache_dir)
16  : cache_dir_{std::move(cache_dir)},
17  hasher_{std::move(hasher)},
18  logger_{log::createLogger("WAVM Module Cache", "runtime_cache")} {
19  BOOST_ASSERT(hasher_ != nullptr);
20  }
21 
22  std::vector<WAVM::U8> ModuleCache::getCachedObject(
23  const WAVM::U8 *wasmBytes,
24  WAVM::Uptr numWASMBytes,
25  std::function<std::vector<WAVM::U8>()> &&compileThunk) {
26  auto runtime_hash =
27  hasher_->twox_64(gsl::span(wasmBytes, numWASMBytes)).toHex();
28  auto filepath = cache_dir_ / runtime_hash;
29  if (!exists(filepath) and !exists(cache_dir_)
31  SL_ERROR(
32  logger_, "Failed to create runtimes cache directory {}", cache_dir_);
33  }
34 
35  std ::vector<WAVM::U8> module;
36  if (std::ifstream file{filepath.c_str(), std::ios::in | std::ios::binary};
37  file.is_open()) {
38  auto module_size = file_size(filepath);
39  module.resize(module_size);
40  file.read(reinterpret_cast<char *>(module.data()), module_size);
41  if (not file.fail()) {
42  SL_VERBOSE(logger_, "WAVM runtime cache hit: {}", filepath);
43  } else {
44  module.clear();
45  SL_ERROR(logger_, "Error reading cached module: {}", filepath);
46  }
47  }
48  if (module.empty()) {
49  module = compileThunk();
50  if (auto file =
51  std::ofstream{filepath.c_str(), std::ios::out | std::ios::binary};
52  file.is_open()) {
53  file.write(reinterpret_cast<char *>(module.data()), module.size());
54  file.close();
55  if (not file.fail()) {
56  SL_VERBOSE(logger_, "Saved WAVM runtime to cache: {}", filepath);
57  } else {
58  module.clear();
59  SL_ERROR(logger_, "Error writing module to cache: {}", filepath);
60  }
61  } else {
62  SL_ERROR(logger_, "Failed to cache WAVM runtime: {}", filepath);
63  }
64  }
65 
66  return module;
67  }
68 } // namespace kagome::runtime::wavm
bool createDirectoryRecursive(const path &path)
Definition: directories.hpp:18
std::shared_ptr< crypto::Hasher > hasher_
std::vector< WAVM::U8 > getCachedObject(const WAVM::U8 *wasmBytes, WAVM::Uptr numWASMBytes, std::function< std::vector< WAVM::U8 >()> &&compileThunk) override
Logger createLogger(const std::string &tag)
Definition: logger.cpp:112
ModuleCache(std::shared_ptr< crypto::Hasher > hasher, fs::path cache_dir)