Action Engine
Loading...
Searching...
No Matches
consistent_hash.h
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef ACTIONENGINE_DISTRIBUTED_CONSISTENT_HASH_H_
16#define ACTIONENGINE_DISTRIBUTED_CONSISTENT_HASH_H_
17
18#include <vector>
19
20#include <absl/container/flat_hash_map.h>
21#include <absl/crc/crc32c.h>
22#include <absl/log/check.h>
23
24namespace act::distributed {
25
26absl::crc32c_t DefaultHash(std::string_view data);
27
28using Hash = absl::AnyInvocable<absl::crc32c_t(std::string_view) const>;
29
30class ConsistentMap {
31 public:
32 explicit ConsistentMap(int32_t replicas, Hash hash = &DefaultHash);
33
34 [[nodiscard]] bool Empty() const;
35
36 void Add(std::initializer_list<std::string_view> keys);
37
38 [[nodiscard]] std::string Get(std::string_view key) const;
39
40 private:
41 Hash hash_;
42 int32_t replicas_ = 1;
43 std::vector<uint32_t> keys_;
44 absl::flat_hash_map<uint32_t, std::string> hash_map_;
45};
46
47} // namespace act::distributed
48
49#endif // ACTIONENGINE_DISTRIBUTED_CONSISTENT_HASH_H_