Kagome
Polkadot Runtime Engine in C++17
offchain_persistent_storage.cpp
Go to the documentation of this file.
1 
7 
10 
11 namespace kagome::offchain {
12 
13  namespace {
14  common::Buffer internalKey(const common::BufferView &key) {
15  const auto &prefix = storage::kOffchainWorkerStoragePrefix;
16  return common::Buffer()
17  .reserve(prefix.size() + key.size())
18  .put(prefix)
19  .put(key);
20  }
21  } // namespace
22 
24  std::shared_ptr<storage::BufferStorage> storage)
25  : storage_(std::move(storage)),
26  log_(log::createLogger("OffchainPersistentStorage", "offchain")) {
27  BOOST_ASSERT(storage_);
28  }
29 
30  outcome::result<void> OffchainPersistentStorageImpl::set(
31  const common::BufferView &key, common::Buffer value) {
32  auto iKey = internalKey(key);
33  std::lock_guard lg(mutex_);
34  return storage_->put(iKey, std::move(value));
35  }
36 
37  outcome::result<void> OffchainPersistentStorageImpl::clear(
38  const common::BufferView &key) {
39  auto iKey = internalKey(key);
40  std::lock_guard lg(mutex_);
41  return storage_->remove(iKey);
42  }
43 
45  const common::BufferView &key,
46  const std::optional<common::BufferView> &expected,
47  common::Buffer value) {
48  auto iKey = internalKey(key);
49  std::lock_guard lg(mutex_);
50  OUTCOME_TRY(get_opt, storage_->tryLoad(iKey));
51 
52  std::optional<common::BufferView> existing;
53  if (get_opt.has_value()) {
54  existing = get_opt.value();
55  }
56 
57  if ((not existing.has_value() and not expected.has_value())
58  or (existing.has_value() and expected.has_value()
59  and existing == expected)) {
60  OUTCOME_TRY(storage_->put(iKey, std::move(value)));
61  return true;
62  }
63  return false;
64  }
65 
66  outcome::result<common::Buffer> OffchainPersistentStorageImpl::get(
67  const common::BufferView &key) {
68  auto iKey = internalKey(key);
69  return storage_->load(iKey);
70  }
71 
72 } // namespace kagome::offchain
Class represents arbitrary (including empty) byte buffer.
Definition: buffer.hpp:29
OffchainPersistentStorageImpl(std::shared_ptr< storage::BufferStorage > storage)
common::BufferView BufferView
outcome::result< void > clear(const common::BufferView &key) override
Remove a value from the local storage.
STL namespace.
const common::Buffer kOffchainWorkerStoragePrefix
outcome::result< void > set(const common::BufferView &key, common::Buffer value) override
Sets a value in the storage.
SLBuffer< std::numeric_limits< size_t >::max()> Buffer
Definition: buffer.hpp:244
outcome::result< bool > compare_and_set(const common::BufferView &key, const std::optional< common::BufferView > &expected, common::Buffer value) override
Sets a new value in the local storage if the condition matches the current value. ...
std::shared_ptr< storage::BufferStorage > storage_
outcome::result< common::Buffer > get(const common::BufferView &key) override
Gets a value from the local storage.
Logger createLogger(const std::string &tag)
Definition: logger.cpp:112