xref: /aosp_15_r20/external/grpc-grpc/src/core/lib/promise/mpsc.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2022 gRPC authors.
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 GRPC_SRC_CORE_LIB_PROMISE_MPSC_H
16 #define GRPC_SRC_CORE_LIB_PROMISE_MPSC_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <stddef.h>
21 
22 #include <algorithm>
23 #include <utility>
24 #include <vector>
25 
26 #include "absl/base/thread_annotations.h"
27 
28 #include <grpc/support/log.h>
29 
30 #include "src/core/lib/gprpp/ref_counted.h"
31 #include "src/core/lib/gprpp/ref_counted_ptr.h"
32 #include "src/core/lib/gprpp/sync.h"
33 #include "src/core/lib/promise/activity.h"
34 #include "src/core/lib/promise/poll.h"
35 #include "src/core/lib/promise/wait_set.h"
36 
37 // Multi producer single consumer inter-activity comms.
38 
39 namespace grpc_core {
40 
41 namespace mpscpipe_detail {
42 
43 // "Center" of the communication pipe.
44 // Contains sent but not received messages, and open/close state.
45 template <typename T>
46 class Center : public RefCounted<Center<T>> {
47  public:
48   // Construct the center with a maximum queue size.
Center(size_t max_queued)49   explicit Center(size_t max_queued) : max_queued_(max_queued) {}
50 
51   // Poll for new items.
52   // - Returns true if new items were obtained, in which case they are contained
53   //   in dest in the order they were added. Wakes up all pending senders since
54   //   there will now be space to send.
55   // - If no new items are available, returns
56   //   false and sets up a waker to be awoken when more items are available.
57   // TODO(ctiller): consider the problem of thundering herds here. There may be
58   // more senders than there are queue spots, and so the strategy of waking up
59   // all senders is ill-advised.
60   // That said, some senders may have been cancelled by the time we wake them,
61   // and so waking a subset could cause starvation.
PollReceiveBatch(std::vector<T> & dest)62   bool PollReceiveBatch(std::vector<T>& dest) {
63     ReleasableMutexLock lock(&mu_);
64     if (queue_.empty()) {
65       receive_waker_ = GetContext<Activity>()->MakeNonOwningWaker();
66       return false;
67     }
68     dest.swap(queue_);
69     queue_.clear();
70     auto wakeups = send_wakers_.TakeWakeupSet();
71     lock.Release();
72     wakeups.Wakeup();
73     return true;
74   }
75 
76   // Poll to send one item.
77   // Returns pending if no send slot was available.
78   // Returns true if the item was sent.
79   // Returns false if the receiver has been closed.
PollSend(T & t)80   Poll<bool> PollSend(T& t) {
81     ReleasableMutexLock lock(&mu_);
82     if (receiver_closed_) return Poll<bool>(false);
83     if (queue_.size() < max_queued_) {
84       queue_.push_back(std::move(t));
85       auto receive_waker = std::move(receive_waker_);
86       lock.Release();
87       receive_waker.Wakeup();
88       return Poll<bool>(true);
89     }
90     send_wakers_.AddPending(GetContext<Activity>()->MakeNonOwningWaker());
91     return Pending{};
92   }
93 
ImmediateSend(T t)94   bool ImmediateSend(T t) {
95     ReleasableMutexLock lock(&mu_);
96     if (receiver_closed_) return false;
97     queue_.push_back(std::move(t));
98     auto receive_waker = std::move(receive_waker_);
99     lock.Release();
100     receive_waker.Wakeup();
101     return true;
102   }
103 
104   // Mark that the receiver is closed.
ReceiverClosed()105   void ReceiverClosed() {
106     ReleasableMutexLock lock(&mu_);
107     if (receiver_closed_) return;
108     receiver_closed_ = true;
109     auto wakeups = send_wakers_.TakeWakeupSet();
110     lock.Release();
111     wakeups.Wakeup();
112   }
113 
114  private:
115   Mutex mu_;
116   const size_t max_queued_;
117   std::vector<T> queue_ ABSL_GUARDED_BY(mu_);
118   bool receiver_closed_ ABSL_GUARDED_BY(mu_) = false;
119   Waker receive_waker_ ABSL_GUARDED_BY(mu_);
120   WaitSet send_wakers_ ABSL_GUARDED_BY(mu_);
121 };
122 
123 }  // namespace mpscpipe_detail
124 
125 template <typename T>
126 class MpscReceiver;
127 
128 // Send half of an mpsc pipe.
129 template <typename T>
130 class MpscSender {
131  public:
132   MpscSender(const MpscSender&) = default;
133   MpscSender& operator=(const MpscSender&) = default;
134   MpscSender(MpscSender&&) noexcept = default;
135   MpscSender& operator=(MpscSender&&) noexcept = default;
136 
137   // Return a promise that will send one item.
138   // Resolves to true if sent, false if the receiver was closed (and the value
139   // will never be successfully sent).
Send(T t)140   auto Send(T t) {
141     return [center = center_, t = std::move(t)]() mutable -> Poll<bool> {
142       if (center == nullptr) return false;
143       return center->PollSend(t);
144     };
145   }
146 
UnbufferedImmediateSend(T t)147   bool UnbufferedImmediateSend(T t) {
148     return center_->ImmediateSend(std::move(t));
149   }
150 
151  private:
152   friend class MpscReceiver<T>;
MpscSender(RefCountedPtr<mpscpipe_detail::Center<T>> center)153   explicit MpscSender(RefCountedPtr<mpscpipe_detail::Center<T>> center)
154       : center_(std::move(center)) {}
155   RefCountedPtr<mpscpipe_detail::Center<T>> center_;
156 };
157 
158 // Receive half of an mpsc pipe.
159 template <typename T>
160 class MpscReceiver {
161  public:
162   // max_buffer_hint is the maximum number of elements we'd like to buffer.
163   // We half this before passing to Center so that the number there is the
164   // maximum number of elements that can be queued in the center of the pipe.
165   // The receiver also holds some of the buffered elements (up to half of them!)
166   // so the total outstanding is equal to max_buffer_hint (unless it's 1 in
167   // which case instantaneosly we may have two elements buffered).
MpscReceiver(size_t max_buffer_hint)168   explicit MpscReceiver(size_t max_buffer_hint)
169       : center_(MakeRefCounted<mpscpipe_detail::Center<T>>(
170             std::max(static_cast<size_t>(1), max_buffer_hint / 2))) {}
~MpscReceiver()171   ~MpscReceiver() {
172     if (center_ != nullptr) center_->ReceiverClosed();
173   }
MarkClosed()174   void MarkClosed() {
175     if (center_ != nullptr) center_->ReceiverClosed();
176   }
177   MpscReceiver(const MpscReceiver&) = delete;
178   MpscReceiver& operator=(const MpscReceiver&) = delete;
179   // Only movable until it's first polled, and so we don't need to contend with
180   // a non-empty buffer during a legal move!
MpscReceiver(MpscReceiver && other)181   MpscReceiver(MpscReceiver&& other) noexcept
182       : center_(std::move(other.center_)) {
183     GPR_DEBUG_ASSERT(other.buffer_.empty());
184   }
185   MpscReceiver& operator=(MpscReceiver&& other) noexcept {
186     GPR_DEBUG_ASSERT(other.buffer_.empty());
187     center_ = std::move(other.center_);
188     return *this;
189   }
190 
191   // Construct a new sender for this receiver.
MakeSender()192   MpscSender<T> MakeSender() { return MpscSender<T>(center_); }
193 
194   // Return a promise that will resolve to the next item (and remove said item).
Next()195   auto Next() {
196     return [this]() -> Poll<T> {
197       if (buffer_it_ != buffer_.end()) {
198         return Poll<T>(std::move(*buffer_it_++));
199       }
200       if (center_->PollReceiveBatch(buffer_)) {
201         buffer_it_ = buffer_.begin();
202         return Poll<T>(std::move(*buffer_it_++));
203       }
204       return Pending{};
205     };
206   }
207 
208  private:
209   // Received items. We move out of here one by one, but don't resize the
210   // vector. Instead, when we run out of items, we poll the center for more -
211   // which swaps this buffer in for the new receive queue and clears it.
212   // In this way, upon hitting a steady state the queue ought to be allocation
213   // free.
214   std::vector<T> buffer_;
215   typename std::vector<T>::iterator buffer_it_ = buffer_.end();
216   RefCountedPtr<mpscpipe_detail::Center<T>> center_;
217 };
218 
219 }  // namespace grpc_core
220 
221 #endif  // GRPC_SRC_CORE_LIB_PROMISE_MPSC_H
222