1
#pragma once
2

            
3
#include <functional>
4

            
5
#include "envoy/init/watcher.h"
6

            
7
#include "source/common/common/logger.h"
8

            
9
namespace Envoy {
10
namespace Init {
11

            
12
/**
13
 * A watcher is just a glorified callback function, called by a target or a manager when
14
 * initialization completes.
15
 */
16
using ReadyFn = std::function<void()>;
17
using TargetAwareReadyFn = std::function<void(absl::string_view)>;
18

            
19
/**
20
 * A WatcherHandleImpl functions as a weak reference to a Watcher. It is how a TargetImpl safely
21
 * notifies a ManagerImpl that it has initialized, and likewise it's how ManagerImpl safely tells
22
 * its client that all registered targets have initialized, with no guarantees about the lifetimes
23
 * of the manager or client.
24
 */
25
class WatcherHandleImpl : public WatcherHandle, Logger::Loggable<Logger::Id::init> {
26
private:
27
  friend class WatcherImpl;
28
  WatcherHandleImpl(absl::string_view handle_name, absl::string_view name,
29
                    std::weak_ptr<TargetAwareReadyFn> fn);
30

            
31
public:
32
  // Init::WatcherHandle.
33
  bool ready() const override;
34

            
35
private:
36
  // Name of the handle (either the name of the target calling the manager, or the name of the
37
  // manager calling the client).
38
  const std::string handle_name_;
39

            
40
  // Name of the watcher (either the name of the manager, or the name of the client).
41
  const std::string name_;
42

            
43
  // The watcher's callback function, only called if the weak pointer can be "locked".
44
  const std::weak_ptr<TargetAwareReadyFn> fn_;
45
};
46

            
47
/**
48
 * A WatcherImpl is an entity that listens for notifications that either an initialization target or
49
 * all targets registered with a manager have initialized. It can only be invoked through a
50
 * WatcherHandleImpl.
51
 */
52
class WatcherImpl : public Watcher, Logger::Loggable<Logger::Id::init> {
53
public:
54
  /**
55
   * @param name a human-readable watcher name, for logging / debugging.
56
   * @param fn a callback function to invoke when `ready` is called on the handle.
57
   */
58
  WatcherImpl(absl::string_view name, ReadyFn fn);
59
  WatcherImpl(absl::string_view name, TargetAwareReadyFn fn);
60
  ~WatcherImpl() override;
61

            
62
  // Init::Watcher.
63
  absl::string_view name() const override;
64
  WatcherHandlePtr createHandle(absl::string_view handle_name) const override;
65

            
66
private:
67
  // Human-readable name for logging.
68
  const std::string name_;
69

            
70
  // The callback function, called via WatcherHandleImpl by either the target or the manager.
71
  const std::shared_ptr<TargetAwareReadyFn> fn_;
72
};
73

            
74
} // namespace Init
75
} // namespace Envoy