1 /** @file
2 
3   @section license License
4 
5   Licensed to the Apache Software Foundation (ASF) under one
6   or more contributor license agreements.  See the NOTICE file
7   distributed with this work for additional information
8   regarding copyright ownership.  The ASF licenses this file
9   to you under the Apache License, Version 2.0 (the
10   "License"); you may not use this file except in compliance
11   with the License.  You may obtain a copy of the License at
12 
13       http://www.apache.org/licenses/LICENSE-2.0
14 
15   Unless required by applicable law or agreed to in writing, software
16   distributed under the License is distributed on an "AS IS" BASIS,
17   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   See the License for the specific language governing permissions and
19   limitations under the License.
20  */
21 
22 #pragma once
23 
24 #include <atomic>
25 #include "Hash.h"
26 #include <cstdint>
27 #include <iostream>
28 #include <map>
29 
30 /*
31   Helper class to be extended to make ring nodes.
32  */
33 
34 struct ATSConsistentHashNode {
35   std::atomic<bool> available;
36   char *name;
37 };
38 
39 std::ostream &operator<<(std::ostream &os, ATSConsistentHashNode &thing);
40 
41 typedef std::map<uint64_t, ATSConsistentHashNode *>::iterator ATSConsistentHashIter;
42 
43 /*
44   TSConsistentHash requires a TSHash64 object
45 
46   Caller is responsible for freeing ring node memory.
47  */
48 
49 struct ATSConsistentHash {
50   ATSConsistentHash(int r = 1024, ATSHash64 *h = nullptr);
51   void insert(ATSConsistentHashNode *node, float weight = 1.0, ATSHash64 *h = nullptr);
52   ATSConsistentHashNode *lookup(const char *url = nullptr, ATSConsistentHashIter *i = nullptr, bool *w = nullptr,
53                                 ATSHash64 *h = nullptr);
54   ATSConsistentHashNode *lookup_available(const char *url = nullptr, ATSConsistentHashIter *i = nullptr, bool *w = nullptr,
55                                           ATSHash64 *h = nullptr);
56   ATSConsistentHashNode *lookup_by_hashval(uint64_t hashval, ATSConsistentHashIter *i = nullptr, bool *w = nullptr);
57   ~ATSConsistentHash();
58 
59 private:
60   int replicas;
61   ATSHash64 *hash;
62   std::map<uint64_t, ATSConsistentHashNode *> NodeMap;
63 };
64