COROIO: coroio/actors/threaded_inbound.hpp Source File
COROIO
Loading...
Searching...
No Matches
threaded_inbound.hpp
1#pragma once
2
3#include "actorsystem.hpp"
4
5#include <coroio/accept_errors.hpp>
6#include <coroio/grow_mailbox.hpp>
7#include <coroio/notifier.hpp>
8
9#include <atomic>
10#include <chrono>
11#include <functional>
12#include <iostream>
13#include <memory>
14#include <string>
15#include <system_error>
16#include <vector>
17
18namespace NNet {
19namespace NActors {
20
21#ifndef _WIN32
22
23// TODO: a batch is allocated on every read and freed on the actor thread. Recycle batches
24// through a return queue with a cap on spares, as TThreadedNode does with its segments.
27 std::vector<TEnvelope> Envelopes;
29 size_t Bytes = 0;
30};
31
52class TQueuedDelivery {
53public:
54 static constexpr size_t DefaultLimit = 16 * 1024 * 1024;
55
56 explicit TQueuedDelivery(TActorSystem& system, size_t limit = DefaultLimit)
57 : System_(system)
58 , Limit_(limit)
59 , Notifier_(system.CreateNotifier())
60 , Consumer_(Consume())
61 { }
62
65 Consumer_ = TFuture<void>();
66 }
67
68 TQueuedDelivery(const TQueuedDelivery&) = delete;
69 TQueuedDelivery& operator=(const TQueuedDelivery&) = delete;
70
72 bool Full() const {
73 return Queued_.load(std::memory_order_relaxed) >= Limit_;
74 }
75
77 void Deliver(std::unique_ptr<TEnvelopeBatch> batch) {
78 // Relaxed: the count orders nothing, the batch itself goes through Queue_
79 Queued_.fetch_add(batch->Bytes, std::memory_order_relaxed);
80 Queue_.Push(std::move(batch));
81 Notifier_->Notify();
82 }
83
85 size_t QueuedBytes() const {
86 return Queued_.load(std::memory_order_relaxed);
87 }
88
89private:
90 static constexpr size_t MaxBytesBeforeYield = 2 * 1024 * 1024;
91
92 // Actor side. A failed wait is logged and tried again after a second, as in TThreadedNode.
93 TFuture<void> WaitForWork() {
94 try {
95 co_await Notifier_->Wait();
96 co_return;
97 } catch (const std::exception& ex) {
98 std::cerr << "Error waiting for inbound envelopes: " << ex.what() << "\n";
99 }
100 co_await System_.Sleep(std::chrono::milliseconds(1000));
101 }
102
103 // Actor side
104 TFuture<void> Consume() {
105 size_t delivered = 0;
106 while (true) {
107 auto popped = Queue_.Pop();
108 if (!popped) {
109 co_await WaitForWork();
110 continue;
111 }
112 auto* batch = popped->get();
113 for (auto& envelope : batch->Envelopes) {
114 System_.Send(envelope.Sender, envelope.Recipient, envelope.MessageId, std::move(envelope.Blob));
115 }
116 Queued_.fetch_sub(batch->Bytes, std::memory_order_relaxed);
117 delivered += batch->Bytes;
118 // Not Yield(): resumed from a timer, it is resumed again in the same pass (issue 244)
119 if (delivered >= MaxBytesBeforeYield) {
120 delivered = 0;
121 co_await System_.Sleep(std::chrono::nanoseconds(1));
122 }
123 }
124 }
125
126 TActorSystem& System_;
127 const size_t Limit_;
128 std::unique_ptr<INotifier> Notifier_;
129 TGrowMailbox<std::unique_ptr<TEnvelopeBatch>> Queue_;
130 std::atomic<size_t> Queued_ = 0;
131 TFuture<void> Consumer_;
132};
133
190template<typename TPoller, typename TDelivery, typename TEnvelopeReader = TZeroCopyEnvelopeReader>
192public:
193 using TSocket = typename TPoller::TSocket;
194
202 TThreadedInbound(TPoller& poller, TSocket listener, TNodeId nodeId, TDelivery& delivery, std::function<void(const std::string&)> logger = {})
203 : TThreadedInbound(poller, std::move(listener), nodeId, delivery, nullptr, std::move(logger))
204 { }
205
208 TThreadedInbound(TPoller& poller, TSocket listener, TNodeId nodeId, TDelivery& delivery, const TMessagesFactory& factory, std::function<void(const std::string&)> logger = {})
209 : TThreadedInbound(poller, std::move(listener), nodeId, delivery, &factory, std::move(logger))
210 { }
211
214 Acceptor_ = TFuture<void>();
215 Connections_.clear();
216 }
217
218 TThreadedInbound(const TThreadedInbound&) = delete;
219 TThreadedInbound& operator=(const TThreadedInbound&) = delete;
220
222 size_t Connections() const {
223 return Connections_.size();
224 }
225
226private:
227 TThreadedInbound(TPoller& poller, TSocket listener, TNodeId nodeId, TDelivery& delivery, const TMessagesFactory* factory, std::function<void(const std::string&)> logger)
228 : Poller_(poller)
229 , Listener_(std::move(listener))
230 , NodeId_(nodeId)
231 , Delivery_(delivery)
232 , Factory_(factory)
233 , Logger_(std::move(logger))
234 , Acceptor_(Accept())
235 { }
236
237 struct TConnection {
238 explicit TConnection(TSocket socket)
239 : Socket(std::move(socket))
240 { }
241
242 TSocket Socket;
243 // Declared after Socket, so it is destroyed first
244 TFuture<void> Reader;
245 };
246
247 static constexpr size_t ReadSize = 512 * 1024;
248 static constexpr size_t InflightBytes = 16 * 1024 * 1024;
249 static constexpr size_t MaxBytesBeforeYield = 2 * 1024 * 1024;
250
251 TFuture<void> Accept() {
252 while (true) {
253 auto client = co_await Listener_.Accept();
254 if (client) {
255 std::erase_if(Connections_, [](const auto& connection) {
256 return connection->Reader.done();
257 });
258 client->SetNoDelay();
259 auto& connection = *Connections_.emplace_back(std::make_unique<TConnection>(std::move(*client)));
260 connection.Reader = Read(connection.Socket);
261 } else if (!IsTransientAcceptError(client.error())) {
262 if (Logger_) {
263 Logger_("Accept failed: " + std::system_category().message(client.error()));
264 }
265 co_await Poller_.Sleep(std::chrono::milliseconds(100));
266 }
267 }
268 }
269
270 // False if the deserializer throws: the envelope is then dropped
271 bool Deserialize(TEnvelope& envelope) {
272 try {
273 envelope.Blob = Factory_->DeserializeFar(envelope.MessageId, std::move(envelope.Blob));
274 return true;
275 } catch (const std::exception& e) {
276 if (Logger_) {
277 Logger_("Cannot deserialize message " + std::to_string(envelope.MessageId)
278 + " for " + envelope.Recipient.ToString() + ": " + e.what());
279 }
280 return false;
281 }
282 }
283
284 TFuture<void> Read(TSocket& socket) {
285 TEnvelopeReader envelopeReader(InflightBytes, /*lowWatermark = */ 1024);
286 size_t bytesRead = 0;
287 try {
288 while (true) {
289 while (Delivery_.Full()) {
290 co_await Poller_.Sleep(std::chrono::milliseconds(1));
291 }
292 auto buffer = envelopeReader.Acquire(ReadSize);
293 auto size = co_await socket.ReadSome(buffer.data(), buffer.size());
294 if (size < 0) {
295 continue;
296 }
297 if (size == 0) {
298 throw std::runtime_error("Socket closed");
299 }
300 envelopeReader.Commit(size);
301
302 std::unique_ptr<TEnvelopeBatch> batch;
303 while (auto envelope = envelopeReader.Pop()) {
304 if (envelope->Recipient.NodeId() != NodeId_) [[unlikely]] {
305 if (Logger_) {
306 Logger_("Received message for different node: " + envelope->Recipient.ToString());
307 }
308 continue;
309 }
310 const size_t bytes = envelope->Blob.Size + sizeof(THeader);
311 if (Factory_ && !Deserialize(*envelope)) {
312 continue;
313 }
314 if (!batch) {
315 batch = std::make_unique<TEnvelopeBatch>();
316 }
317 batch->Bytes += bytes;
318 batch->Envelopes.push_back(std::move(*envelope));
319 }
320 if (batch) {
321 Delivery_.Deliver(std::move(batch));
322 }
323
324 // A read that does not block does not suspend: without this a busy peer
325 // would keep the loop from the other connections. Not Yield(), see TThreadedNode.
326 bytesRead += size;
327 if (bytesRead >= MaxBytesBeforeYield) {
328 bytesRead = 0;
329 co_await Poller_.Sleep(std::chrono::nanoseconds(1));
330 }
331 }
332 } catch (const std::exception& e) {
333 if (Logger_) {
334 Logger_(std::string("Error in InboundConnection: ") + e.what());
335 }
336 }
337 socket.Close();
338 }
339
340 TPoller& Poller_;
341 TSocket Listener_;
342 TNodeId NodeId_;
343 TDelivery& Delivery_;
344 const TMessagesFactory* Factory_;
345 std::function<void(const std::string&)> Logger_;
346 std::vector<std::unique_ptr<TConnection>> Connections_;
347 TFuture<void> Acceptor_;
348};
349
350#endif // _WIN32
351
352} // namespace NActors
353} // namespace NNet
auto Sleep(TTime until)
Suspends the current coroutine until until. Delegates to the poller.
Definition actor.hpp:857
std::unique_ptr< INotifier > CreateNotifier()
Creates a notifier on the poller thread. The poller must outlive it.
Definition actor.cpp:28
Single-threaded actor runtime.
Definition actorsystem.hpp:61
Serializers and deserializers of message types, by message id.
Definition messages_factory.hpp:21
Delivery of TThreadedInbound to an actor system on another thread.
Definition threaded_inbound.hpp:52
bool Full() const
I/O side: true while the connections must not read.
Definition threaded_inbound.hpp:72
~TQueuedDelivery()
Destroys the coroutine first: it waits on the notifier and pops the queue.
Definition threaded_inbound.hpp:64
size_t QueuedBytes() const
Bytes handed over and not passed to Send yet. Any thread.
Definition threaded_inbound.hpp:85
void Deliver(std::unique_ptr< TEnvelopeBatch > batch)
I/O side.
Definition threaded_inbound.hpp:77
Accepts and reads the inbound connections of an actor system on an I/O thread.
Definition threaded_inbound.hpp:191
size_t Connections() const
Connections accepted and not forgotten yet. On the I/O thread, or while its loop does not run.
Definition threaded_inbound.hpp:222
~TThreadedInbound()
Destroys the coroutines first: they wait on the sockets.
Definition threaded_inbound.hpp:213
TThreadedInbound(TPoller &poller, TSocket listener, TNodeId nodeId, TDelivery &delivery, const TMessagesFactory &factory, std::function< void(const std::string &)> logger={})
Definition threaded_inbound.hpp:208
TThreadedInbound(TPoller &poller, TSocket listener, TNodeId nodeId, TDelivery &delivery, std::function< void(const std::string &)> logger={})
Definition threaded_inbound.hpp:202
High-level asynchronous socket for network communication.
Definition socket.hpp:406
Envelopes of one read of an inbound connection, on their way from its I/O thread to the actors.
Definition threaded_inbound.hpp:26
size_t Bytes
Payload and header bytes of the envelopes.
Definition threaded_inbound.hpp:29
Definition corochain.hpp:74