FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
rest_channel.hpp
Go to the documentation of this file.
1#pragma once
2// RestChannel: reactor-driven keep-alive HTTP(S) for the venue requests that run on the net thread
3// (depth snapshots, openOrders, execution replays, listenKey keepalive, and the order traffic that
4// goes over REST: orders falling back from the WebSocket, cancel-all, dead man's switch refreshes).
5//
6// HTTP/1.1 answers one request at a time per connection, so a channel with one connection makes a
7// cancel wait for every snapshot and replay page queued ahead of it. The channel therefore has two
8// lanes, each with its own connection and queue:
9//
10// RestLane::Control everything else: reference data, snapshots, reconciliation, replays
11// RestLane::Orders orders, cancels and the requests that keep orders safe (cancel-all, the
12// dead man's switch): they wait for nothing but each other
13//
14// A lane hands its client one request at a time and keeps the rest. When a connection that was up
15// fails, only the request on it fails; the ones behind it go out on the next connection. When a
16// connection cannot be made (refused, TLS failure, connect timeout, no address), every request of
17// the lane fails with that error and the host is resolved again for the next attempt, so a venue
18// that moved its addresses is found again. Lookups run off the net thread (net::AsyncResolver):
19// the first starts when the channel is made.
20//
21// With endpoint selection (net/endpoint_selector.hpp, select_endpoint) the lookups also probe the
22// host's addresses and each connection goes to the fastest; an address a connection could not be
23// made to is passed over by the next. A lane keeps its connection while it lasts: it moves to a
24// faster address when it next connects.
25//
26// Requests are std::function/std::string based: control path only.
27#include "fastmm/net/dns.hpp"
28#include "fastmm/net/endpoint_selector.hpp"
31#include "fastmm/net/source_address.hpp"
32#include "fastmm/net/tls_stream.hpp"
33#include "fastmm/net/url.hpp"
34
35#include <array>
36#include <cstddef>
37#include <cstdint>
38#include <cstring>
39#include <deque>
40#include <memory>
41#include <optional>
42#include <stdexcept>
43#include <string>
44#include <string_view>
45#include <utility>
46#include <vector>
47
48namespace fastmm::venues {
49
50struct RestChannelConfig {
51 std::string base_url; // https://host[:port][/prefix]
52 std::string ca_file;
53 bool insecure_tls = false;
54 std::uint32_t timeout_ms = 5000; // per request once written; the connect and the lookup too
55 std::size_t max_queue = 8; // per lane, the request in flight included
56 net::SourceAddress source; // where the connection leaves this host from; empty: anywhere
57 std::optional<bool> select_endpoint; // endpoint selection; nullopt: the process's default
58};
60// Queue room for a connector's REST channel with `symbols` subscribed: every connector fans some
61// requests out per symbol (cancel-all, the USDⓈ-M countdown, execution and funding replays), and
62// those can overlap, on top of a fixed set (reconciliation, clock, listen key, the dead man's
63// switch, orders falling back to REST). The queue is a deque: room costs nothing until used.
64[[nodiscard]] constexpr std::size_t rest_queue_for(std::size_t symbols) noexcept {
65 return 32 + 4 * symbols;
67
68// The RestChannelConfig every connector config spells the same way.
69template <class Cfg>
70[[nodiscard]] RestChannelConfig rest_channel_config(const Cfg& cfg, std::size_t symbols) {
71 RestChannelConfig rc;
72 rc.base_url = cfg.rest_url;
73 rc.ca_file = cfg.ca_file;
74 rc.insecure_tls = cfg.insecure_tls;
75 rc.timeout_ms = cfg.http_timeout_ms;
76 rc.max_queue = rest_queue_for(symbols);
77 if constexpr (requires { cfg.source; }) rc.source = cfg.source;
78 if constexpr (requires { cfg.select_endpoint; }) rc.select_endpoint = cfg.select_endpoint;
79 return rc;
80}
81
82enum class RestLane : std::uint8_t { Control = 0, Orders = 1 };
83
85 public:
91 : reactor_(reactor), cfg_(std::move(cfg)), resolver_(reactor) {
92 const auto url = net::Url::parse(cfg_.base_url);
93 if (!url) throw std::invalid_argument("RestChannel: bad base url '" + cfg_.base_url + "'");
94 host_ = std::string(url->host);
95 port_ = url->port;
96 use_tls_ = url->tls;
97 prefix_ = url->path == "/" ? std::string{} : std::string(url->path);
98 while (!prefix_.empty() && prefix_.back() == '/') prefix_.pop_back();
99 if (use_tls_) tls_ctx_ = net::TlsContext::shared_client(cfg_.ca_file, cfg_.insecure_tls);
100 if (net::EndpointSelector& sel = net::EndpointSelector::instance();
101 sel.selects(cfg_.select_endpoint))
102 endpoints_ = sel.host(host_, port_, cfg_.source);
103 start_resolve();
104 }
105 ~RestChannel() {
106 cancel_resolve_timer();
108 }
109 RestChannel(const RestChannel&) = delete;
110 RestChannel& operator=(const RestChannel&) = delete;
112 // `target` is the path plus query without the base prefix. The callback runs on the reactor
113 // thread, once; a transport failure arrives as HttpResponse::error != None. Returns false (and
114 // never calls back) when the lane's queue is full.
115 bool request(std::string_view method,
116 std::string_view target,
117 std::string_view extra_headers,
118 std::string_view body,
119 Callback cb,
121 Pending p;
122 p.target = prefix_ + std::string(target);
123 return enqueue(lane, method, extra_headers, body, std::move(p), std::move(cb));
124 }
125
126 // The same, with the target (without the base prefix) made when the request is written, not
127 // when it is queued: a signed query is stamped and signed then, however long it waited in its
128 // lane. Empty: not sent, the callback gets NetError::Canceled.
129 bool request(std::string_view method,
130 net::HttpTargetMaker make_target,
131 std::string_view extra_headers,
132 std::string_view body,
133 Callback cb,
135 if (!make_target) return false;
136 Pending p;
137 p.make_target = [prefix = prefix_, make = std::move(make_target)] {
138 std::string target = make();
139 return target.empty() ? target : prefix + target;
140 };
141 return enqueue(lane, method, extra_headers, body, std::move(p), std::move(cb));
142 }
143
144 // Closes both connections; every request waiting or in flight gets NetError::Canceled. The
145 // channel stays usable: the next request connects again. Not from inside one of its callbacks.
146 void reset() noexcept {
147 for (Lane& l : lanes_) {
148 std::deque<Pending> waiting;
149 waiting.swap(l.waiting);
150 for (Pending& p : waiting) fail(p, net::NetError::Canceled, "closed");
151 l.plain.reset();
152 l.tls.reset();
153 l.busy = false;
154 }
155 }
156
157 // For a subscription that grew after connect: see rest_queue_for().
158 void set_max_queue(std::size_t n) noexcept { cfg_.max_queue = n; }
159
160 // Requests of `lane` waiting or in flight.
161 [[nodiscard]] std::size_t queued(RestLane lane = RestLane::Control) const noexcept {
162 const Lane& l = lanes_[index(lane)];
163 return l.waiting.size() + (l.busy ? 1 : 0);
164 }
165 [[nodiscard]] std::size_t max_queue() const noexcept { return cfg_.max_queue; }
166 // The lane has a connection, made or being made.
167 [[nodiscard]] bool connected(RestLane lane) const noexcept {
168 const Lane& l = lanes_[index(lane)];
169 return l.plain != nullptr || l.tls != nullptr;
170 }
171 [[nodiscard]] std::uint64_t requests() const noexcept { return requests_; }
172 [[nodiscard]] std::uint64_t errors() const noexcept { return errors_; }
173 [[nodiscard]] std::uint64_t connects() const noexcept { return connects_; }
174 [[nodiscard]] std::uint64_t lookups() const noexcept { return lookups_; }
175 [[nodiscard]] const std::string& host() const noexcept { return host_; }
176 [[nodiscard]] bool tls() const noexcept { return use_tls_; }
178 private:
179 static constexpr std::size_t kLanes = 2;
180
181 struct Pending {
182 std::string method;
183 std::string target; // with the prefix; empty when make_target makes it
184 net::HttpTargetMaker make_target;
185 std::string headers;
186 std::string body;
187 Callback cb;
188 };
189
190 struct Lane {
191 std::deque<Pending> waiting; // not handed to a client yet
192 std::unique_ptr<PlainClient> plain;
193 std::unique_ptr<TlsClient> tls;
194 bool busy = false; // a request is with the client, its callback has not run
195 net::SockAddr addr; // the peer of the connection
196 };
197
198 static constexpr std::size_t index(RestLane lane) noexcept {
199 return static_cast<std::size_t>(lane);
200 }
201
202 bool enqueue(RestLane lane,
203 std::string_view method,
204 std::string_view headers,
205 std::string_view body,
206 Pending&& p,
207 Callback&& cb) {
208 if (queued(lane) >= cfg_.max_queue) {
209 ++errors_;
210 return false;
211 }
212 p.method = method;
213 p.headers = headers;
214 p.body = body;
215 p.cb = std::move(cb);
216 Lane& l = lanes_[index(lane)];
217 l.waiting.push_back(std::move(p));
218 ++requests_;
219 // An idle open connection takes the request now, also from inside a callback of its own
220 // request (HttpClient takes the next one there). Anything else goes through the reactor: a
221 // connection is never replaced from inside its own callback, and a lookup or a connect that
222 // fails never calls back before request() has returned.
223 const bool ready = (l.plain && l.plain->is_ready()) || (l.tls && l.tls->is_ready());
224 if (ready && !l.busy) {
225 pump(lane);
226 } else if (!l.busy) {
227 schedule_pump();
228 }
229 return true;
230 }
231
232 void fail(Pending& p, net::NetError err, std::string_view detail) {
233 ++errors_;
234 net::HttpResponse r;
235 r.error = err;
236 r.error_detail = detail;
237 r.rx_ts = net::Reactor::now_ns();
238 if (p.cb) p.cb(r);
239 }
240
241 // Every request waiting in `lane` fails with `err` (the connection cannot be made).
242 void fail_waiting(Lane& l, net::NetError err, std::string_view detail) {
243 std::deque<Pending> waiting;
244 waiting.swap(l.waiting);
245 for (Pending& p : waiting) fail(p, err, detail);
246 }
247
248 void schedule_pump() {
249 if (pump_pending_) return;
250 pump_pending_ = true;
251 std::weak_ptr<int> alive = alive_;
252 reactor_.post([this, alive] {
253 if (alive.expired()) return;
254 pump_pending_ = false;
255 pump(RestLane::Control);
256 pump(RestLane::Orders);
257 });
258 }
259
260 // Hands the lane's next request to its client, connecting first when it has none. From inside a
261 // client's callback only when that client is open and idle (enqueue), so it is never replaced
262 // there.
263 void pump(RestLane lane) {
264 Lane& l = lanes_[index(lane)];
265 if (l.busy || l.waiting.empty()) return;
266 if (l.plain && l.plain->state() == net::HttpClientState::Closed) l.plain.reset();
267 if (l.tls && l.tls->state() == net::HttpClientState::Closed) l.tls.reset();
268 if (!l.plain && !l.tls && !open(lane)) return;
269 Pending p = std::move(l.waiting.front());
270 l.waiting.pop_front();
271 l.busy = true; // before the hand-over: a request the client refuses calls back at once
272 auto cb = [this, lane, alive = std::weak_ptr<int>(alive_), user = std::move(p.cb)](
273 const net::HttpResponse& r) {
274 if (alive.expired()) return;
275 done(lane, r, user);
276 };
277 const bool taken = p.make_target ? hand(l, p.method, std::move(p.make_target), p, cb)
278 : hand(l, p.method, std::string_view(p.target), p, cb);
279 if (!taken) {
280 l.busy = false;
281 ++errors_;
282 net::HttpResponse r;
283 r.error = net::NetError::InvalidState;
284 r.error_detail = "connection refused the request";
285 cb(r);
286 }
287 }
288
289 template <class Target, class Cb>
290 bool hand(Lane& l, std::string_view method, Target&& target, const Pending& p, Cb& cb) {
291 if (l.plain)
292 return l.plain->request(method, std::forward<Target>(target), p.headers, p.body, cb);
293 return l.tls->request(method, std::forward<Target>(target), p.headers, p.body, cb);
294 }
295
296 // The client answered the lane's request, or failed it.
297 void done(RestLane lane, const net::HttpResponse& r, const Callback& user) {
298 Lane& l = lanes_[index(lane)];
299 l.busy = false;
300 if (r.error != net::NetError::None) {
301 ++errors_;
302 // A connection that never came up fails everything behind it as well, and the next attempt
303 // looks the host up again.
304 const bool closed = (l.plain && l.plain->state() == net::HttpClientState::Closed) ||
305 (l.tls && l.tls->state() == net::HttpClientState::Closed);
306 const bool established =
307 (l.plain && l.plain->established()) || (l.tls && l.tls->established());
308 if (closed && !established && r.error != net::NetError::Canceled) {
309 addrs_stale_ = true;
310 if (endpoints_) endpoints_->failed(l.addr);
311 if (user) user(r);
312 fail_waiting(l, r.error, r.error_detail);
313 schedule_pump();
314 return;
315 }
316 }
317 if (user) user(r);
318 schedule_pump();
319 }
320
321 // Makes the lane's connection. False when there is none yet: the lookup is running (its answer
322 // pumps the lanes) or the connect failed (the lane's requests have failed).
323 bool open(RestLane lane) {
324 Lane& l = lanes_[index(lane)];
325 if (addrs_.empty() || addrs_stale_) {
326 wait_for_lookup();
327 return false;
328 }
329 net::TcpSocket sock;
330 net::SockAddr addr = addrs_[addr_index_++ % addrs_.size()];
331 if (endpoints_) {
332 if (const std::optional<net::EndpointChoice> c = endpoints_->acquire(/*lease=*/false)) {
333 addr = c->addr;
334 if (!same_peer(addr, logged_)) {
335 logged_ = addr;
336 net::log_endpoint_choice(
337 lane == RestLane::Orders ? "rest orders" : "rest", *endpoints_, *c);
338 }
339 }
340 }
341 l.addr = addr;
342 const std::optional<net::SockAddr> local = net::source_bind_address(cfg_.source, addr.family());
343 if (sock.connect(addr, local ? &*local : nullptr) == net::ConnectStatus::Error) {
344 addrs_stale_ = true;
345 if (endpoints_) endpoints_->failed(addr);
346 fail_waiting(l, net::NetError::Syscall, "connect failed");
347 return false;
348 }
349 sock.set_nodelay(true);
350 net::HttpClientConfig hc;
351 hc.timeout_ms = cfg_.timeout_ms;
352 hc.max_queue = 1; // the lane keeps the queue
353 ++connects_;
354 bool started = false;
355 if (use_tls_) {
356 l.tls = std::make_unique<TlsClient>(
357 reactor_,
358 net::TlsStream<net::PlainStream>(*tls_ctx_, net::PlainStream(std::move(sock)), host_),
359 host_,
360 port_,
361 true,
362 hc);
363 started = l.tls->start();
364 if (!started) l.tls.reset();
365 } else {
366 l.plain = std::make_unique<PlainClient>(
367 reactor_, net::PlainStream(std::move(sock)), host_, port_, false, hc);
368 started = l.plain->start();
369 if (!started) l.plain.reset();
370 }
371 if (!started) {
372 fail_waiting(l, net::NetError::Syscall, "connection not registered");
373 return false;
374 }
375 // A connect refused at once (loopback) closes the client inside start().
376 const bool closed = (l.plain && l.plain->state() == net::HttpClientState::Closed) ||
377 (l.tls && l.tls->state() == net::HttpClientState::Closed);
378 if (closed) {
379 addrs_stale_ = true;
380 if (endpoints_) endpoints_->failed(addr);
381 fail_waiting(l, net::NetError::Syscall, "connect failed");
382 return false;
383 }
384 return true;
385 }
386
387 // Looks the host up unless a lookup is running. The constructor's lookup has nothing waiting for
388 // it; a lane that waits arms the timeout (wait_for_lookup).
389 void start_resolve() {
390 if (resolving_) return;
391 resolving_ = true;
392 ++lookups_;
393 std::weak_ptr<int> alive = alive_;
394 auto done = [this, alive](net::ResolveResult r) {
395 if (alive.expired()) return;
396 resolving_ = false;
397 cancel_resolve_timer();
398 if (r.ok()) {
399 net::keep_reachable(cfg_.source, r.addrs);
400 if (!r.addrs.empty()) addrs_ = std::move(r.addrs);
401 }
402 if (addrs_.empty()) {
403 const std::string_view why =
404 r.ok() ? "no address of the source's family" : "host lookup failed";
405 for (Lane& l : lanes_) fail_waiting(l, net::NetError::Resolve, why);
406 return;
407 }
408 // A failed refresh keeps the addresses it had: the lanes try them again.
409 addrs_stale_ = false;
410 pump(RestLane::Control);
411 pump(RestLane::Orders);
412 };
413 if (endpoints_) {
414 resolver_.resolve(endpoints_, std::move(done));
415 } else {
416 resolver_.resolve(host_, port_, std::move(done));
417 }
418 }
419
420 static bool same_peer(const net::SockAddr& a, const net::SockAddr& b) noexcept {
421 return a.len == b.len && std::memcmp(&a.storage, &b.storage, a.len) == 0;
422 }
423
424 // A lookup that hangs (an unreachable DNS server) fails the requests waiting for it after the
425 // request timeout; its answer, whenever it comes, is still kept for the next ones.
426 void wait_for_lookup() {
427 start_resolve();
428 if (resolve_timer_ != net::kInvalidTimer) return;
429 resolve_timer_ =
430 reactor_.add_timer_after(static_cast<std::int64_t>(cfg_.timeout_ms) * 1'000'000, [this] {
431 resolve_timer_ = net::kInvalidTimer;
432 if (!resolving_) return;
433 for (Lane& l : lanes_) fail_waiting(l, net::NetError::Timeout, "host lookup timed out");
434 });
435 }
436
437 void cancel_resolve_timer() noexcept {
438 if (resolve_timer_ != net::kInvalidTimer) {
439 reactor_.cancel_timer(resolve_timer_);
440 resolve_timer_ = net::kInvalidTimer;
441 }
442 }
443
444 net::Reactor& reactor_;
445 RestChannelConfig cfg_;
446 std::string host_;
447 std::uint16_t port_ = 0;
448 bool use_tls_ = false;
449 std::string prefix_;
450 std::shared_ptr<const net::TlsContext> tls_ctx_;
451 std::array<Lane, kLanes> lanes_;
452 net::AsyncResolver resolver_;
453 std::shared_ptr<net::EndpointHost> endpoints_; // set: endpoint selection
454 net::SockAddr logged_; // the address the last log line named
455 std::vector<net::SockAddr> addrs_;
456 std::size_t addr_index_ = 0;
457 bool addrs_stale_ = false;
458 bool resolving_ = false;
459 net::TimerId resolve_timer_ = net::kInvalidTimer;
460 bool pump_pending_ = false;
461 std::shared_ptr<int> alive_ = std::make_shared<int>(0);
462 std::uint64_t requests_ = 0;
463 std::uint64_t errors_ = 0;
464 std::uint64_t connects_ = 0;
465 std::uint64_t lookups_ = 0;
466};
467
468} // namespace fastmm::venues
Definition http_client.hpp:118
Definition reactor.hpp:72
TimerId add_timer_after(std::int64_t delay_ns, TimerCallback cb)
Definition reactor.hpp:105
bool cancel_timer(TimerId id) noexcept
void post(Task task)
Thread-safe: queue a task for the reactor thread and wake it.
static std::int64_t now_ns() noexcept
CLOCK_MONOTONIC.
Definition rest_channel.hpp:86
const std::string & host() const noexcept
Definition rest_channel.hpp:177
std::size_t queued(RestLane lane=RestLane::Control) const noexcept
Requests of lane waiting or in flight.
Definition rest_channel.hpp:163
bool connected(RestLane lane) const noexcept
The lane has a connection, made or being made.
Definition rest_channel.hpp:169
std::uint64_t lookups() const noexcept
Definition rest_channel.hpp:176
std::uint64_t connects() const noexcept
Definition rest_channel.hpp:175
std::size_t max_queue() const noexcept
Definition rest_channel.hpp:167
bool tls() const noexcept
Definition rest_channel.hpp:178
std::uint64_t requests() const noexcept
Definition rest_channel.hpp:173
bool request(std::string_view method, std::string_view target, std::string_view extra_headers, std::string_view body, Callback cb, RestLane lane=RestLane::Control)
target is the path plus query without the base prefix.
Definition rest_channel.hpp:117
net::HttpResponseCallback Callback
Definition rest_channel.hpp:88
void reset() noexcept
Closes both connections; every request waiting or in flight gets NetError::Canceled.
Definition rest_channel.hpp:148
std::uint64_t errors() const noexcept
Definition rest_channel.hpp:174
RestChannel & operator=(const RestChannel &)=delete
~RestChannel()
Definition rest_channel.hpp:107
void set_max_queue(std::size_t n) noexcept
For a subscription that grew after connect: see rest_queue_for().
Definition rest_channel.hpp:160
Keep-alive HTTP/1.1 client over any ByteStream: one request in flight per connection plus a small FIF...
std::uint64_t TimerId
Definition reactor.hpp:69
std::function< void(const HttpResponse &)> HttpResponseCallback
Definition http_client.hpp:41
constexpr TimerId kInvalidTimer
Definition reactor.hpp:70
std::function< std::string()> HttpTargetMaker
Makes a request's target (path and query) when the request is written.
Definition http_client.hpp:44
Definition venue.hpp:39
RestChannelConfig rest_channel_config(const Cfg &cfg, std::size_t symbols)
The RestChannelConfig every connector config spells the same way.
Definition rest_channel.hpp:72
RestLane
Definition rest_channel.hpp:84
constexpr std::size_t rest_queue_for(std::size_t symbols) noexcept
Queue room for a connector's REST channel with symbols subscribed: every connector fans some requests...
Definition rest_channel.hpp:66
@ Error
venue-level error payload
@ Pending
orders on their way: sent, not yet working, or a requote waiting its turn
Single-threaded event loop with a timer min-heap and a thread-safe mailbox (post/wake via eventfd),...
static std::optional< Url > parse(std::string_view s) noexcept
Accepts scheme://host[:port][/path][?query].
Definition url.hpp:38
Definition rest_channel.hpp:52
std::optional< bool > select_endpoint
endpoint selection; nullopt: the process's default
Definition rest_channel.hpp:59
std::string base_url
https://host[:port][/prefix]
Definition rest_channel.hpp:53
std::string ca_file
Definition rest_channel.hpp:54
bool insecure_tls
Definition rest_channel.hpp:55
net::SourceAddress source
where the connection leaves this host from; empty: anywhere
Definition rest_channel.hpp:58
std::size_t max_queue
per lane, the request in flight included
Definition rest_channel.hpp:57
std::uint32_t timeout_ms
per request once written; the connect and the lookup too
Definition rest_channel.hpp:56
Minimal URL parsing / query building for venue endpoints.