Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
polled_link.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <cstring>
6#include <memory>
7#include <span>
8#include <vector>
9
10// Servicing a broker's sockets from its own worker thread, with no receive threads and
11// no hand-off between threads: whatever arrives goes from the socket to the protocol
12// session in the loop iteration that finds it. Templated on the socket types, a
13// caller-driven ("polled") TCP client and multicast receiver, so this header depends on
14// no socket library, and a test can drive it with fakes.
15namespace slick::trader {
16
17// The connection a protocol session talks over.
19public:
20 virtual ~ByteTransport() = default;
21 virtual void send(const uint8_t* data, size_t size) = 0;
22 // Drops the connection at the link's next service(), never from inside the
23 // session's own callback.
24 virtual void close() = 0;
25};
26
27// TCP delivers a stream: a message may end in a later read. Hands the consumer what has
28// arrived and keeps the tail it did not take.
30public:
31 // `consume(const uint8_t*, size_t) -> size_t` returns how many bytes it took.
32 template <typename Consume>
33 void feed(const uint8_t* data, size_t size, Consume&& consume) {
34 if (partial_.empty()) {
35 const size_t consumed = consume(data, size);
36 if (consumed < size) {
37 append(data + consumed, size - consumed);
38 }
39 } else {
40 append(data, size);
41 const size_t consumed = consume(partial_.data(), partial_.size());
42 partial_.erase(partial_.begin(), partial_.begin() + static_cast<std::ptrdiff_t>(consumed));
43 }
44 }
45 void clear() noexcept { partial_.clear(); }
46 [[nodiscard]] size_t pending() const noexcept { return partial_.size(); }
47
48private:
49 // resize + memcpy rather than vector::insert/assign with an iterator range: GCC 12-14 inlines
50 // the range copy into the callers and warns (-Wstringop-overflow) that it writes into a region
51 // of size 0, which it cannot, since the vector was just grown to hold it.
52 void append(const uint8_t* data, size_t size) {
53 const size_t old_size = partial_.size();
54 partial_.resize(old_size + size);
55 std::memcpy(partial_.data() + old_size, data, size);
56 }
57
58 std::vector<uint8_t> partial_;
59};
60
61// One TCP connection serviced by its owner's worker: made, read, handed to the session,
62// and made again after `reconnect_ns` when it drops.
63//
64// `Client` has the polled TCP client's interface: State {Disconnected, Connecting,
65// Connected}, state(), poll(), connect(), disconnect(), is_connected(),
66// receive(std::span<uint8_t>) and send(std::span<const uint8_t>).
67//
68// The session given to service() has on_connected(now), on_data(data, size, now) ->
69// bytes consumed, on_timer(now), on_disconnected() and ready_to_connect(now) -> bool.
70template <typename Client>
71class PolledLink : public ByteTransport {
72public:
73 PolledLink(std::unique_ptr<Client> client, uint64_t reconnect_ns)
74 : client_(std::move(client))
75 , reconnect_ns_(reconnect_ns)
76 {}
77
78 void send(const uint8_t* data, size_t size) override {
79 // Straight from the session's buffer to the socket. A failed send has closed the
80 // connection: the session is told on the next service().
81 client_->send(std::span<const uint8_t>(data, size));
82 }
83 void close() override { close_requested_ = true; }
84
85 // Connects, reads and runs the session's timer; true when anything was read.
86 template <typename Session>
87 bool service(Session& session, uint64_t now_ns, std::span<uint8_t> buffer, int max_reads = 16) {
88 using State = typename Client::State;
89 bool worked = false;
90 if (client_->state() == State::Connecting) {
91 client_->poll(); // made, failed or timed out
92 }
93 if (client_->state() == State::Connected) {
94 if (!connected_) {
95 connected_ = true;
96 close_requested_ = false;
97 assembler_.clear();
98 session.on_connected(now_ns);
99 }
100 for (int i = 0; i < max_reads && !close_requested_; ++i) {
101 const std::ptrdiff_t received = client_->receive(buffer);
102 if (received <= 0) {
103 break; // nothing waiting, or the connection is gone (handled below)
104 }
105 worked = true;
106 assembler_.feed(buffer.data(), static_cast<size_t>(received), [&](const uint8_t* data, size_t size) {
107 return session.on_data(data, size, now_ns);
108 });
109 }
110 if (client_->is_connected() && !close_requested_) {
111 session.on_timer(now_ns);
112 }
113 }
114 if (close_requested_) {
115 // The session asked for the connection to be dropped: done here rather than
116 // from inside its callbacks.
117 close_requested_ = false;
118 client_->disconnect();
119 }
120 if (client_->state() == State::Disconnected) {
121 if (connected_) {
122 connected_ = false;
123 assembler_.clear();
124 next_connect_ns_ = now_ns + reconnect_ns_;
125 session.on_disconnected();
126 }
127 if (enabled_ && now_ns >= next_connect_ns_ && session.ready_to_connect(now_ns)) {
128 next_connect_ns_ = now_ns + reconnect_ns_;
129 client_->connect();
130 }
131 }
132 return worked;
133 }
134
135 // Drops the connection without telling the session: the owner is shutting down.
136 void disconnect() {
137 client_->disconnect();
138 connected_ = false;
139 assembler_.clear();
140 }
141
142 // A link that is not enabled is not connected again once it drops.
143 void set_enabled(bool enabled) noexcept { enabled_ = enabled; }
144 // Makes the next service() connect at once, whatever the reconnect pacing says.
145 void connect_now() noexcept { next_connect_ns_ = 0; }
146
147 // The session has been told it is connected.
148 [[nodiscard]] bool connected() const noexcept { return connected_; }
149 [[nodiscard]] Client& client() noexcept { return *client_; }
150
151private:
152 std::unique_ptr<Client> client_;
153 uint64_t reconnect_ns_;
154 uint64_t next_connect_ns_ = 0;
155 StreamAssembler assembler_;
156 bool connected_ = false;
157 bool close_requested_ = false;
158 bool enabled_ = true;
159};
160
161// A multicast line needed only some of the time (a snapshot or definition loop). Its
162// socket stays joined but is not read while unwanted: leaving and rejoining a group
163// takes longer than a gap is allowed to. What piled up unread is stale by the time it is
164// wanted again, and is thrown away first.
165//
166// `Receiver` has receive(std::span<uint8_t>) -> bytes, 0 or less for none.
167template <typename Receiver>
169public:
170 GatedLine() = default;
171 explicit GatedLine(std::unique_ptr<Receiver> receiver) : receiver_(std::move(receiver)) {}
172
173 // While `wanted`, applies up to `max` packets with `apply(const uint8_t*, size_t)`;
174 // returns how many. What piled up while it was not wanted is thrown away first and
175 // counted in discarded().
176 template <typename Apply>
177 uint32_t read(bool wanted, std::span<uint8_t> buffer, uint32_t max, Apply&& apply) {
178 discarded_ = 0;
179 if (!receiver_) {
180 return 0;
181 }
182 if (wanted && !reading_) {
183 while (receiver_->receive(buffer) > 0) {
184 ++discarded_;
185 }
186 }
187 reading_ = wanted;
188 if (!wanted) {
189 return 0;
190 }
191 uint32_t applied = 0;
192 for (; applied < max; ++applied) {
193 const std::ptrdiff_t size = receiver_->receive(buffer);
194 if (size <= 0) {
195 break;
196 }
197 apply(buffer.data(), static_cast<size_t>(size));
198 }
199 return applied;
200 }
201
202 void reset(std::unique_ptr<Receiver> receiver) {
203 receiver_ = std::move(receiver);
204 reading_ = false;
205 }
206 [[nodiscard]] Receiver* receiver() noexcept { return receiver_.get(); }
207 // Packets the last read() threw away: they show the group is live, though unused.
208 [[nodiscard]] uint32_t discarded() const noexcept { return discarded_; }
209
210private:
211 std::unique_ptr<Receiver> receiver_;
212 uint32_t discarded_ = 0;
213 bool reading_ = false;
214};
215
216} // namespace slick::trader
virtual void send(const uint8_t *data, size_t size)=0
virtual ~ByteTransport()=default
uint32_t read(bool wanted, std::span< uint8_t > buffer, uint32_t max, Apply &&apply)
void reset(std::unique_ptr< Receiver > receiver)
Receiver * receiver() noexcept
uint32_t discarded() const noexcept
GatedLine(std::unique_ptr< Receiver > receiver)
void feed(const uint8_t *data, size_t size, Consume &&consume)
size_t pending() const noexcept