aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/ZooKeeper/ZooKeeperNodeCache.h
blob: 2167b8bd11b6fcb91130c0094fa2a60f3945db4c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once

#include <unordered_map>
#include <unordered_set>
#include <mutex>
#include <memory>
#include <optional>
#include <Poco/Event.h>
#include "ZooKeeper.h"
#include "Common.h"

namespace DB
{
    namespace ErrorCodes
    {
    }
}

namespace zkutil
{

/// This class allows querying the contents of ZooKeeper nodes and caching the results.
/// Watches are set for cached nodes and for nodes that were nonexistent at the time of query.
/// After a watch fires, the callback or event that was passed by the user is notified.
///
/// NOTE: methods of this class are not thread-safe.
///
/// Intended use case: if you need one thread to watch changes in several nodes.
/// If instead you use simple a watch event for this, watches will accumulate for nodes that do not change
/// or change rarely.
class ZooKeeperNodeCache
{
public:
    explicit ZooKeeperNodeCache(GetZooKeeper get_zookeeper);

    ZooKeeperNodeCache(const ZooKeeperNodeCache &) = delete;
    ZooKeeperNodeCache(ZooKeeperNodeCache &&) = default;

    struct ZNode
    {
        bool exists = false;
        std::string contents;
        Coordination::Stat stat{};
    };

    ZNode get(const std::string & path, EventPtr watch_event);
    ZNode get(const std::string & path, Coordination::WatchCallback watch_callback);

private:
    GetZooKeeper get_zookeeper;

    struct Context
    {
        std::mutex mutex;
        std::unordered_set<std::string> invalidated_paths;
        bool all_paths_invalidated = false;
    };

    std::shared_ptr<Context> context;

    std::unordered_map<std::string, ZNode> path_to_cached_znode;
};

}