COROIO: coroio/actors/threaded_node.hpp Source File
COROIO
Loading...
Searching...
No Matches
threaded_node.hpp
1#pragma once
2
3#include "node.hpp"
4#include "output_buffer.hpp"
5
6#include <coroio/grow_mailbox.hpp>
7#include <coroio/notifier.hpp>
8
9#include <atomic>
10#include <mutex>
11#include <vector>
12
13namespace NNet {
14namespace NActors {
15
16#ifndef _WIN32
17
19struct TNullLock {
20 void lock() {
21 }
22
23 void unlock() {
24 }
25};
26
83template<typename TPoller, typename TLock = TNullLock>
84class TThreadedNode final : public INode {
85public:
86 using TSocket = typename TPoller::TSocket;
87
90 static constexpr size_t MaxSpareSegments = 4;
91
101 TThreadedNode(TPoller& poller, TMessagesFactory& factory, TResolver& resolver, const std::function<TSocket(const TAddress&)>& socketFactory, const THostPort& hostPort)
102 : Poller_(poller)
103 , Factory_(factory)
104 , Resolver_(resolver)
105 , SocketFactory_(socketFactory)
106 , HostPort_(hostPort)
107 , Notifier_(poller)
108 , Current_(std::make_unique<TSegment>(Segments_))
109 , Server_(Serve())
110 {
111 Spare_.reserve(MaxSpareSegments);
112 }
113
117 Server_ = TFuture<void>();
118 }
119
121 TLock& ProducerLock() {
122 return Lock_;
123 }
124
127 size_t Segments() const {
128 return Segments_.load(std::memory_order_relaxed);
129 }
130
131 // The framing is the one of TNode::Send; a deferred payload is left to the I/O side
132 void Send(TEnvelope&& envelope) override {
133 // Empty blobs skip the factory and its compile-time check of the id
134 if (envelope.MessageId > MaxMessageId) [[unlikely]] {
135 throw std::invalid_argument("message id " + std::to_string(envelope.MessageId)
136 + " overlaps the padding bits of THeader::MessageId");
137 }
138 std::lock_guard guard(Lock_);
139 auto blob = std::move(envelope.Blob);
140 uint32_t padding = 0;
141 uint32_t payload = 0;
142 const TMessagesFactory::TPayloadWriter* writer = nullptr;
143 if (blob.Size > 0) {
144 if (blob.Type == TBlob::PointerType::Near) {
145 writer = Factory_.PayloadWriter(envelope.MessageId);
146 }
147 if (writer) {
148 // Sized here: an invalid object throws to the sender, as with TNode
149 payload = writer->Size(blob);
150 } else {
151 blob = Factory_.SerializeFar(envelope.MessageId, std::move(blob));
152 payload = blob.Size;
153 }
154 const size_t alignment = Factory_.PayloadAlignment(envelope.MessageId);
155 if (alignment > 1) {
156 padding = PayloadPadding(Offset(), alignment);
157 }
158 }
159 THeader data{
160 .Sender = envelope.Sender,
161 .Recipient = envelope.Recipient,
162 .MessageId = envelope.MessageId | (padding << HeaderPaddingShift),
163 .Size = payload
164 };
165 const size_t size = sizeof(data) + padding + payload;
166 auto buf = Acquire(size);
167 std::memcpy(buf.data(), &data, sizeof(data));
168 std::memset(buf.data() + sizeof(data), 0, padding);
169 if (writer) {
170 Current_->Deferred.push_back(TDeferredPayload{
171 .Offset = Current_->Size + sizeof(data) + padding,
172 .Size = payload,
173 .Write = writer->Write,
174 .Blob = std::move(blob),
175 });
176 } else if (payload > 0) {
177 std::memcpy(buf.data() + sizeof(data) + padding, blob.Data.get(), payload);
178 }
179 Commit(size);
180 }
181
182 std::span<char> Acquire(size_t size) override {
183 auto& segment = *Current_;
184 segment.Data.Reserve(segment.Size, segment.Size + size);
185 return std::span<char>(segment.Data.Data() + segment.Size, size);
186 }
187
188 void Commit(size_t size) override {
189 Current_->Size += size;
190 }
191
192 uint64_t Offset() const override {
193 if (!WroteAligned_) [[unlikely]] {
194 // One atomic step against the CAS in Connect(): either that moved the base first
195 // and this reads the new one, or it sees the bit and keeps the base. The word
196 // carries all the two sides share here, so nothing is ordered by it: relaxed.
197 Base_ = AlignState_.fetch_or(AlignedBit, std::memory_order_relaxed) >> 1;
198 WroteAligned_ = true;
199 }
200 return SealedBytes_ + Current_->Size - Base_;
201 }
202
203 void StartConnect() override {
204 std::lock_guard guard(Lock_);
205 Activate();
206 }
207
208 void Drain() override {
209 std::lock_guard guard(Lock_);
210 Activate();
211 if (Current_->Size == 0) {
212 return;
213 }
214 auto next = TakeSpare();
215 next->Size = 0;
216 SealedBytes_ += Current_->Size;
217 Current_.swap(next);
218 Queue_.Push(std::move(next));
219 Notifier_.Notify();
220 }
221
222 THostPort GetHostPort() const override {
223 return HostPort_;
224 }
225
226private:
227 // A payload that the I/O side writes into its frame, at Offset of the segment
228 struct TDeferredPayload {
229 size_t Offset = 0;
230 uint32_t Size = 0;
231 // Taken in Send: the I/O side does not read the factory
232 TMessagesFactory::TPayloadWrite Write = nullptr;
233 TBlob Blob;
234 };
235
236 // Frames committed between two Drain calls. The buffer keeps its memory while the
237 // segment goes around: producer, Queue_, I/O side, Returned_, Spare_, producer.
238 struct TSegment {
239 // Counts itself: Segments() is what the node really holds, whatever path a segment took
240 explicit TSegment(std::atomic<size_t>& live)
241 : Live(live)
242 {
243 Live.fetch_add(1, std::memory_order_relaxed);
244 }
245
246 ~TSegment() {
247 Live.fetch_sub(1, std::memory_order_relaxed);
248 }
249
250 TSegment(const TSegment&) = delete;
251 TSegment& operator=(const TSegment&) = delete;
252
253 std::atomic<size_t>& Live;
254 // Not zero-filled: every byte below Size is written before the segment is sent, the
255 // padding by the producer and the payload holes by WritePayloads
256 TOutputBuffer Data;
257 size_t Size = 0;
258 // In the order of their frames; empty again once the I/O side has written them
259 std::vector<TDeferredPayload> Deferred;
260 };
261
262 // AlignState_ is the stream base shifted left by one, with this bit set once
263 // a frame with PayloadAlignment has been written
264 static constexpr uint64_t AlignedBit = 1;
265 static constexpr size_t MaxBytesBeforeYield = 2 * 1024 * 1024;
266
267 // Producer side
268 void Activate() {
269 if (!Active_) {
270 Active_ = true;
271 // Release pairs with the acquire load in Serve(): the notification alone
272 // tells the I/O side to look, not what to see.
273 ConnectRequested_.store(true, std::memory_order_release);
274 Notifier_.Notify();
275 }
276 }
277
278 // Producer side. The segment returned last comes first: a backlog that has passed
279 // does not send every spare buffer around again.
280 std::unique_ptr<TSegment> TakeSpare() {
281 while (auto segment = Returned_.Pop()) {
282 Spare_.push_back(std::move(*segment));
283 }
284 if (Spare_.empty()) {
285 return std::make_unique<TSegment>(Segments_);
286 }
287 auto segment = std::move(Spare_.back());
288 Spare_.pop_back();
289 SpareCount_.fetch_sub(1, std::memory_order_relaxed);
290 return segment;
291 }
292
293 // I/O side. Only this side adds to SpareCount_, so the check keeps it at the cap.
294 // Relaxed: the count orders nothing, the segment itself goes through Returned_.
295 void Recycle(std::unique_ptr<TSegment> segment) {
296 if (SpareCount_.load(std::memory_order_relaxed) < MaxSpareSegments) {
297 SpareCount_.fetch_add(1, std::memory_order_relaxed);
298 Returned_.Push(std::move(segment));
299 }
300 }
301
302 // I/O side. The objects die here: a recycled segment must not bring them back.
303 void WritePayloads(TSegment& segment) noexcept {
304 for (const auto& payload : segment.Deferred) {
305 payload.Write(payload.Blob, std::span<char>(segment.Data.Data() + payload.Offset, payload.Size));
306 }
307 segment.Deferred.clear();
308 }
309
310 // I/O side. A failed wait is logged and tried again after the back-off: the node
311 // then looks for work once a second instead of never.
312 TFuture<void> WaitForWork() {
313 try {
314 co_await Notifier_.Wait();
315 co_return;
316 } catch (const std::exception& ex) {
317 std::cerr << "Error waiting for frames to " << HostPort_.ToString() << ": " << ex.what() << "\n";
318 }
319 co_await Poller_.Sleep(std::chrono::milliseconds(1000));
320 }
321
322 // I/O side
323 TFuture<void> Serve() {
324 // Like TNode, the node does not connect before StartConnect() or Drain()
325 while (!ConnectRequested_.load(std::memory_order_acquire)) {
326 co_await WaitForWork();
327 }
328 while (true) {
329 if (!Connected_) {
330 co_await Connect();
331 }
332 auto segment = Queue_.Pop();
333 if (!segment) {
334 co_await WaitForWork();
335 continue;
336 }
337 Writing_ = std::move(*segment);
338 // Counted before the write: a failed write drops the rest of the segment, as in TNode
339 SentBytes_ += Writing_->Size;
340 WritePayloads(*Writing_);
341 try {
342 co_await TByteWriter(Socket_).Write(Writing_->Data.Data(), Writing_->Size);
343 } catch (const std::exception& ex) {
344 std::cerr << "Error during draining: " << ex.what() << "\n";
345 Connected_ = false;
346 }
347 WrittenBytes_ += Writing_->Size;
348 Recycle(std::move(Writing_));
349 // A write that does not block does not suspend: without this a busy producer
350 // would keep the loop from its other coroutines. Not Yield(): resumed from
351 // a timer, it is resumed again in the same pass, before the poller polls.
352 if (WrittenBytes_ >= MaxBytesBeforeYield) {
353 WrittenBytes_ = 0;
354 co_await Poller_.Sleep(std::chrono::nanoseconds(1));
355 }
356 }
357 }
358
359 // I/O side
360 TFuture<void> Connect() {
361 // Without aligned frames the new stream starts at 0 with no filler, as TNode does:
362 // the base moves to the first byte of the new stream. Once the bit is set the base
363 // stays, and the filler below gives the queued frames their old offsets.
364 uint64_t state = AlignState_.load(std::memory_order_relaxed);
365 while (!(state & AlignedBit) && !AlignState_.compare_exchange_weak(state, SentBytes_ << 1,
366 std::memory_order_relaxed, std::memory_order_relaxed))
367 {
368 }
369 const uint64_t offset = (state & AlignedBit) ? SentBytes_ - (state >> 1) : 0;
370 std::cout << "Connecting to " << HostPort_.ToString() << "\n";
371 while (!Connected_) {
372 try {
373 TAddress addr = co_await HostPort_.Resolve(Resolver_);
374 Socket_ = SocketFactory_(addr);
375 // Small messages (acks) must not wait for Nagle and delayed ACK.
376 Socket_.SetNoDelay();
377 co_await Socket_.Connect(addr);
378 char filler[MaxFillerSize];
379 if (const size_t size = WriteFiller(filler, offset)) {
380 co_await TByteWriter(Socket_).Write(filler, size);
381 }
382 Connected_ = true;
383 std::cout << "Connected to " << HostPort_.ToString() << "\n";
384 } catch (const std::exception& ex) {
385 std::cerr << "Error connecting to " << HostPort_.ToString() << ": " << ex.what() << "\n";
386 Connected_ = false;
387 }
388 if (!Connected_) {
389 co_await Poller_.Sleep(std::chrono::milliseconds(1000));
390 }
391 }
392 }
393
394 TPoller& Poller_;
395 TMessagesFactory& Factory_;
396 TResolver& Resolver_;
397 std::function<TSocket(TAddress&)> SocketFactory_;
398 THostPort HostPort_;
399
400 // Shared by the two sides
401 TNotifier<TPoller> Notifier_;
402 // Declared before every owner of a segment, so it outlives the segments
403 std::atomic<size_t> Segments_ = 0;
404 TGrowMailbox<std::unique_ptr<TSegment>> Queue_;
405 TGrowMailbox<std::unique_ptr<TSegment>> Returned_;
406 std::atomic<bool> ConnectRequested_ = false;
407 // Segments in Returned_ and Spare_
408 std::atomic<size_t> SpareCount_ = 0;
409 mutable std::atomic<uint64_t> AlignState_ = 0;
410
411 // Producer side, under Lock_
412 TLock Lock_;
413 std::unique_ptr<TSegment> Current_;
414 // Taken from Returned_, newest last
415 std::vector<std::unique_ptr<TSegment>> Spare_;
416 // Bytes of the segments handed to the I/O side
417 uint64_t SealedBytes_ = 0;
418 bool Active_ = false;
419 // Set by Offset(), with the base it took from AlignState_
420 mutable bool WroteAligned_ = false;
421 mutable uint64_t Base_ = 0;
422
423 // I/O side
424 bool Connected_ = false;
425 TSocket Socket_;
426 std::unique_ptr<TSegment> Writing_;
427 // Bytes of the segments taken from Queue_, written or dropped: the count the producer
428 // side keeps in SealedBytes_, as the I/O side has seen it
429 uint64_t SentBytes_ = 0;
430 // Since the I/O coroutine last let the loop poll
431 size_t WrittenBytes_ = 0;
432 TFuture<void> Server_;
433};
434
435#endif // _WIN32
436
437} // namespace NActors
438} // namespace NNet
Interface for a remote node connection in the actor transport layer.
Definition node.hpp:23
Message envelope containing routing and payload information.
Definition actor.hpp:125
Serializers and deserializers of message types, by message id.
Definition messages_factory.hpp:21
void(*)(const TBlob &blob, std::span< char > out) noexcept TPayloadWrite
Writes the payload of the object in a Near blob into out, which has its size.
Definition messages_factory.hpp:24
void Commit(size_t size) override
Marks size previously acquired bytes as ready to send.
Definition threaded_node.hpp:188
~TThreadedNode()
Definition threaded_node.hpp:116
TThreadedNode(TPoller &poller, TMessagesFactory &factory, TResolver &resolver, const std::function< TSocket(const TAddress &)> &socketFactory, const THostPort &hostPort)
Constructs the node and its I/O coroutine; does not connect.
Definition threaded_node.hpp:101
TLock & ProducerLock()
The lock of the producer side. Hold it across Offset, Acquire and Commit of one frame.
Definition threaded_node.hpp:121
size_t Segments() const
Definition threaded_node.hpp:127
uint64_t Offset() const override
Definition threaded_node.hpp:192
void Send(TEnvelope &&envelope) override
Serializes envelope and appends it to the outbound buffer.
Definition threaded_node.hpp:132
THostPort GetHostPort() const override
Returns the remote host:port this node connects to.
Definition threaded_node.hpp:222
std::span< char > Acquire(size_t size) override
Definition threaded_node.hpp:182
static constexpr size_t MaxSpareSegments
Definition threaded_node.hpp:90
void Drain() override
Calls StartConnect() then asynchronously writes all buffered bytes to the socket.
Definition threaded_node.hpp:208
void StartConnect() override
Initiates an async TCP connection if not already connected or connecting.
Definition threaded_node.hpp:203
A class representing an IPv4 or IPv6 address (with port).
Definition address.hpp:38
A host:port pair that resolves to a TAddress.
Definition resolver.hpp:261
Async DNS resolver over UDP.
Definition resolver.hpp:115
Opaque message payload with Near/Far duality.
Definition messages.hpp:101
@ Near
Live object pointer — valid only within the same process.
Definition messages.hpp:106
Wire header prepended to every remote actor message.
Definition actorid.hpp:103
The payload writer of a type, see RegisterPayloadWriter.
Definition messages_factory.hpp:27
TPayloadWrite Write
SerializeTo of that object, which must not throw.
Definition messages_factory.hpp:31
uint32_t(* Size)(const TBlob &blob)
FarPayloadSize of the object in a Near blob; may throw.
Definition messages_factory.hpp:29
Producer lock of TThreadedNode for a single producer thread: locks nothing.
Definition threaded_node.hpp:19
Definition corochain.hpp:74