|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <launchdarkly/async/promise.hpp> |
| 4 | + |
| 5 | +#include <condition_variable> |
| 6 | +#include <map> |
| 7 | +#include <memory> |
| 8 | +#include <mutex> |
| 9 | +#include <thread> |
| 10 | + |
| 11 | +// This file implements a cancellation primitive modelled after C++20's |
| 12 | +// std::stop_source / std::stop_token / std::stop_callback design: a source |
| 13 | +// owns the ability to trigger cancellation, lightweight tokens (derived from |
| 14 | +// the source) can be freely passed around, and CancellationCallback provides |
| 15 | +// RAII registration of a callback tied to a token. |
| 16 | + |
| 17 | +namespace launchdarkly::async { |
| 18 | + |
| 19 | +// CancellationState is the shared state between a CancellationSource and all |
| 20 | +// CancellationTokens and CancellationCallbacks derived from it. This is an |
| 21 | +// internal class; use CancellationSource, CancellationToken, and |
| 22 | +// CancellationCallback instead. |
| 23 | +class CancellationState { |
| 24 | + public: |
| 25 | + using CallbackId = std::size_t; |
| 26 | + |
| 27 | + // Sentinel returned by Register() when the state was already cancelled; |
| 28 | + // the callback is invoked immediately in that case. Deregister() is a |
| 29 | + // no-op for this value. |
| 30 | + static constexpr CallbackId kAlreadyCancelled = 0; |
| 31 | + |
| 32 | + CancellationState() = default; |
| 33 | + ~CancellationState() = default; |
| 34 | + CancellationState(CancellationState const&) = delete; |
| 35 | + CancellationState& operator=(CancellationState const&) = delete; |
| 36 | + CancellationState(CancellationState&&) = delete; |
| 37 | + CancellationState& operator=(CancellationState&&) = delete; |
| 38 | + |
| 39 | + // Registers a callback and returns its ID. If Cancel() has already been |
| 40 | + // called, invokes cb immediately (outside the lock) and returns |
| 41 | + // kAlreadyCancelled. |
| 42 | + CallbackId Register(Continuation<void()> cb) { |
| 43 | + std::unique_lock lock(mutex_); |
| 44 | + if (cancelled_) { |
| 45 | + lock.unlock(); |
| 46 | + cb(); |
| 47 | + return kAlreadyCancelled; |
| 48 | + } |
| 49 | + CallbackId id = next_id_++; |
| 50 | + callbacks_.emplace(id, std::move(cb)); |
| 51 | + return id; |
| 52 | + } |
| 53 | + |
| 54 | + // Deregisters the callback with the given ID. If the callback is currently |
| 55 | + // executing on another thread, blocks until execution completes. This |
| 56 | + // mirrors the synchronization guarantee of C++20's stop_callback |
| 57 | + // destructor: after Deregister returns, the callback is guaranteed to have |
| 58 | + // either never run or fully completed. No-op if id is kAlreadyCancelled or |
| 59 | + // the callback has already run. |
| 60 | + void Deregister(CallbackId id) { |
| 61 | + if (id == kAlreadyCancelled) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + std::unique_lock lock(mutex_); |
| 66 | + |
| 67 | + // The callback is still pending: remove it before it can run. |
| 68 | + if (callbacks_.erase(id)) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + // The callback has already run, or was never registered. |
| 73 | + if (executing_id_ != id) { |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + // The callback is executing on this thread (re-entrant call from |
| 78 | + // within the callback itself): return without waiting to avoid |
| 79 | + // deadlock. |
| 80 | + if (executing_thread_ == std::this_thread::get_id()) { |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + // The callback is executing on another thread. Wait for it to |
| 85 | + // finish. executing_id_ is set while the state lock is held — before |
| 86 | + // unlocking for invocation — so there is no window where the callback |
| 87 | + // is running but executing_id_ is not yet set. |
| 88 | + executing_done_.wait(lock, [this, id] { return executing_id_ != id; }); |
| 89 | + } |
| 90 | + |
| 91 | + // Invokes all registered callbacks in registration order, then clears the |
| 92 | + // pending list. Callbacks are executed one at a time with the lock |
| 93 | + // released during each invocation to prevent deadlocks. No-op if called |
| 94 | + // more than once. |
| 95 | + void Cancel() { |
| 96 | + std::unique_lock lock(mutex_); |
| 97 | + if (cancelled_) { |
| 98 | + return; |
| 99 | + } |
| 100 | + cancelled_ = true; |
| 101 | + |
| 102 | + while (!callbacks_.empty()) { |
| 103 | + // Extract the next entry while still holding the lock, then set |
| 104 | + // executing_id_ before releasing. This ensures Deregister can |
| 105 | + // never observe a window where the callback is running but |
| 106 | + // executing_id_ is unset. |
| 107 | + auto node = callbacks_.extract(callbacks_.begin()); |
| 108 | + executing_id_ = node.key(); |
| 109 | + executing_thread_ = std::this_thread::get_id(); |
| 110 | + |
| 111 | + lock.unlock(); |
| 112 | + node.mapped()(); |
| 113 | + lock.lock(); |
| 114 | + |
| 115 | + executing_id_ = kAlreadyCancelled; |
| 116 | + lock.unlock(); |
| 117 | + executing_done_.notify_all(); |
| 118 | + lock.lock(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + // Returns true if Cancel() has been called. |
| 123 | + bool IsCancelled() const { |
| 124 | + std::lock_guard lock(mutex_); |
| 125 | + return cancelled_; |
| 126 | + } |
| 127 | + |
| 128 | + private: |
| 129 | + mutable std::mutex mutex_; |
| 130 | + bool cancelled_ = false; |
| 131 | + CallbackId next_id_ = 1; // Real IDs start at 1; 0 is kAlreadyCancelled. |
| 132 | + std::map<CallbackId, Continuation<void()>> callbacks_; |
| 133 | + |
| 134 | + // Tracks which callback (if any) is currently being invoked by Cancel(), |
| 135 | + // and on which thread, to support the blocking destructor in Deregister. |
| 136 | + CallbackId executing_id_ = kAlreadyCancelled; |
| 137 | + std::thread::id executing_thread_; |
| 138 | + std::condition_variable executing_done_; |
| 139 | +}; |
| 140 | + |
| 141 | +class CancellationToken; |
| 142 | + |
| 143 | +// CancellationSource is the write end of a cancellation pair: call Cancel() |
| 144 | +// to signal all operations holding tokens derived from this source. |
| 145 | +// |
| 146 | +// CancellationSource is copyable; copies share the same underlying |
| 147 | +// CancellationState, matching the behaviour of C++20's stop_source. |
| 148 | +class CancellationSource { |
| 149 | + public: |
| 150 | + CancellationSource() : state_(std::make_shared<CancellationState>()) {} |
| 151 | + |
| 152 | + ~CancellationSource() = default; |
| 153 | + CancellationSource(CancellationSource const&) = default; |
| 154 | + CancellationSource& operator=(CancellationSource const&) = default; |
| 155 | + CancellationSource(CancellationSource&&) = default; |
| 156 | + CancellationSource& operator=(CancellationSource&&) = default; |
| 157 | + |
| 158 | + // Invokes all registered callbacks in registration order. No-op if called |
| 159 | + // more than once. |
| 160 | + void Cancel() { state_->Cancel(); } |
| 161 | + |
| 162 | + // Returns true if Cancel() has been called. |
| 163 | + bool IsCancelled() const { return state_->IsCancelled(); } |
| 164 | + |
| 165 | + // Returns a token referring to this source's cancellation state. The |
| 166 | + // token may be freely copied and passed to any number of |
| 167 | + // CancellationCallbacks. |
| 168 | + CancellationToken GetToken() const; |
| 169 | + |
| 170 | + private: |
| 171 | + std::shared_ptr<CancellationState> state_; |
| 172 | +}; |
| 173 | + |
| 174 | +// CancellationToken is the read end of a cancellation pair. Tokens are |
| 175 | +// obtained from CancellationSource::GetToken() and passed to |
| 176 | +// CancellationCallback constructors to register callbacks. |
| 177 | +// |
| 178 | +// A default-constructed token has no associated state: any |
| 179 | +// CancellationCallback constructed from it is never invoked. |
| 180 | +// |
| 181 | +// CancellationToken is cheap to copy; all copies share the same underlying |
| 182 | +// CancellationState. |
| 183 | +class CancellationToken { |
| 184 | + public: |
| 185 | + CancellationToken() = default; |
| 186 | + |
| 187 | + explicit CancellationToken(std::shared_ptr<CancellationState> state) |
| 188 | + : state_(std::move(state)) {} |
| 189 | + |
| 190 | + // Returns true if the associated source has been cancelled, or false if |
| 191 | + // there is no associated source. |
| 192 | + bool IsCancelled() const { return state_ && state_->IsCancelled(); } |
| 193 | + |
| 194 | + private: |
| 195 | + std::shared_ptr<CancellationState> state_; |
| 196 | + |
| 197 | + friend class CancellationCallback; |
| 198 | +}; |
| 199 | + |
| 200 | +inline CancellationToken CancellationSource::GetToken() const { |
| 201 | + return CancellationToken(state_); |
| 202 | +} |
| 203 | + |
| 204 | +// CancellationCallback registers a callback to be invoked when the associated |
| 205 | +// CancellationSource is cancelled. The callback is invoked on whichever thread |
| 206 | +// calls CancellationSource::Cancel(). |
| 207 | +// |
| 208 | +// The design follows C++20's std::stop_callback: |
| 209 | +// |
| 210 | +// - Constructing a CancellationCallback registers the callback. If the |
| 211 | +// source was already cancelled, the callback is invoked immediately in the |
| 212 | +// constructor. |
| 213 | +// - Destroying a CancellationCallback deregisters the callback. If the |
| 214 | +// callback is currently executing on another thread, the destructor blocks |
| 215 | +// until execution completes, preventing use-after-free of anything captured |
| 216 | +// by the callback. |
| 217 | +// - CancellationCallback is non-copyable and non-movable, matching C++20's |
| 218 | +// stop_callback. |
| 219 | +class CancellationCallback { |
| 220 | + public: |
| 221 | + CancellationCallback(CancellationToken token, Continuation<void()> cb) |
| 222 | + : state_(token.state_), |
| 223 | + id_(state_ ? state_->Register(std::move(cb)) |
| 224 | + : CancellationState::kAlreadyCancelled) {} |
| 225 | + |
| 226 | + ~CancellationCallback() { |
| 227 | + if (state_) { |
| 228 | + state_->Deregister(id_); |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + CancellationCallback(CancellationCallback const&) = delete; |
| 233 | + CancellationCallback& operator=(CancellationCallback const&) = delete; |
| 234 | + CancellationCallback(CancellationCallback&&) = delete; |
| 235 | + CancellationCallback& operator=(CancellationCallback&&) = delete; |
| 236 | + |
| 237 | + private: |
| 238 | + std::shared_ptr<CancellationState> state_; |
| 239 | + CancellationState::CallbackId id_; |
| 240 | +}; |
| 241 | + |
| 242 | +} // namespace launchdarkly::async |
0 commit comments