FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
connection.hpp
Go to the documentation of this file.
1#pragma once
2// Resilient WebSocket connection: DNS -> TCP -> TLS -> WS upgrade -> auth -> subscribe ->
3// Live, with stale/dead detection, exponential backoff reconnects, and make-before-break
4// rollover ahead of the venue's connection lifetime limit (Binance: 24 h).
5//
6// Idle -> Resolving -> Connecting -> TlsHandshake -> WsHandshake -> Authenticating
7// -> Subscribing -> Live <-> Stale ; any failure -> Backoff -> Resolving ...
8// close() -> Closing -> Idle (no reconnect)
9//
10// The handler (static dispatch, see ConnectionHandler) receives state changes and messages.
11// on_connected_send_subscriptions() is where the venue layer writes its subscribe/auth
12// payloads with send_text(); Authenticating/Subscribing pass through synchronously unless the
13// config asks for manual acknowledgement (auth_done()/subscribe_done() from the handler when
14// the venue's ack arrives).
15//
16// Rollover: when max_lifetime_ms elapses, a second session is opened while the first keeps
17// delivering; once the new session is Live the old one is closed. Both sessions deliver
18// messages during the overlap (market-data consumers must tolerate duplicates, which the
19// book-sync FSM does by sequence number). Sends target the newest session from its
20// on_ws_open onwards so subscriptions land on the right socket.
21//
22// Endpoint selection (net/endpoint_selector.hpp, cfg.select_endpoint): every lookup also probes
23// the host's addresses, each session connects to the address the host's EndpointHost picks, a
24// session that fails before it is up marks its address failed so the next attempt takes another,
25// and a connection that rolls over (max_lifetime_ms) moves to a faster address by the same
26// make-before-break when its own falls behind.
28#include "fastmm/net/byte_stream.hpp"
29#include "fastmm/net/dns.hpp"
30#include "fastmm/net/endpoint_selector.hpp"
32#include "fastmm/net/source_address.hpp"
33#include "fastmm/net/tls_stream.hpp"
34#include "fastmm/net/url.hpp"
36
37#include <algorithm>
38#include <cstddef>
39#include <cstdint>
40#include <functional>
41#include <memory>
42#include <optional>
43#include <span>
44#include <stdexcept>
45#include <string>
46#include <string_view>
47#include <type_traits>
48#include <utility>
49#include <vector>
50
51namespace fastmm::net {
52
53enum class ConnState : std::uint8_t {
54 Idle,
61 Live,
62 Stale, // Live, but nothing received for stale_ms (sub-state of Live)
63 Closing,
64 Backoff,
65};
66
67std::string_view to_string(ConnState s) noexcept;
68
70 std::string url; // ws:// or wss://host[:port]/path?query
71 struct Tls {
72 std::string ca_file; // trust only this bundle (self-signed sim server)
73 bool insecure = false; // skip verification entirely
74 } tls;
75 std::uint32_t stale_ms = 2000;
76 std::uint32_t dead_ms = 10'000;
78 std::uint64_t max_lifetime_ms = 0; // 0 = never roll over
79 std::uint32_t heartbeat_interval_ms = 0; // 0 = no client pings
80 std::uint32_t connect_timeout_ms = 10'000;
81 // Where the connection leaves this host from (net/source_address.hpp); empty: anywhere. Only
82 // the venue's addresses of a family the source has are tried.
83 SourceAddress source;
84 // Endpoint selection for this connection: true or false, or nullopt for the process's default
85 // (EndpointSelector::selects). Only for a host name; a numeric address is used as it is.
86 std::optional<bool> select_endpoint;
87 bool manual_auth = false; // handler calls auth_done()
88 bool manual_subscribe = false; // handler calls subscribe_done()
89 std::string extra_headers; // "Name: value\r\n" block for the upgrade request
90 // Called before every upgrade request and used instead of extra_headers when set: headers
91 // signed with a fresh nonce (Gemini authenticates the upgrade itself).
92 std::function<std::string()> make_headers;
93 // Venue handlers parse text with simdjson, whose first stage rejects invalid UTF-8; the
94 // WebSocket-level check would scan every message a second time.
96};
98// Throws std::invalid_argument on a bad URL; fills `url` (views into cfg.url).
100
101template <class H>
102concept ConnectionHandler =
103 requires(H& h, ConnState s, std::string_view t, std::span<const std::byte> b, std::int64_t ts) {
104 h.on_state(s);
105 h.on_text(t, ts);
106 h.on_binary(b, ts);
107 h.on_connected_send_subscriptions();
108 };
109
110struct ConnectionStats {
111 std::uint64_t connects = 0; // sessions that reached Live
112 std::uint64_t reconnects = 0; // Backoff entries
113 std::uint64_t rollovers = 0;
114 std::uint64_t stale_events = 0;
115 std::uint64_t dead_events = 0;
116 std::uint64_t frames_rx = 0;
117 std::uint64_t frames_tx = 0;
118 std::uint64_t bytes_rx = 0;
119 std::uint64_t bytes_tx = 0;
120 std::uint64_t drops = 0;
121 std::uint64_t endpoint_moves = 0; // rollovers to a faster address (endpoint selection)
124template <ByteStream Stream, ConnectionHandler Handler>
125class Connection {
126 static constexpr bool kTls = std::is_same_v<Stream, TlsStream<PlainStream>>;
127 static_assert(std::is_same_v<Stream, PlainStream> || kTls,
128 "Connection supports PlainStream and TlsStream<PlainStream>");
129
130 public:
131 // For TLS streams the process's client context for cfg.tls is used unless one is supplied
132 // (TlsContext::shared_client).
133 Connection(Reactor& reactor,
135 Handler& handler,
136 const TlsContext* tls = nullptr)
137 : reactor_(reactor),
138 cfg_(std::move(cfg)),
139 handler_(handler),
140 backoff_(cfg_.backoff),
141 resolver_(reactor) {
142 validate_connection_config(cfg_, url_);
143 if constexpr (kTls) {
144 if (tls == nullptr) {
145 shared_tls_ = TlsContext::shared_client(cfg_.tls.ca_file, cfg_.tls.insecure);
146 tls = shared_tls_.get();
147 }
148 }
149 tls_ = tls;
150 host_ = std::string(url_.host);
151 if (EndpointSelector& sel = EndpointSelector::instance(); sel.selects(cfg_.select_endpoint))
152 endpoints_ = sel.host(host_, url_.port, cfg_.source);
153 // Sized by the URL: a combined-stream path of many symbols is several kilobytes, and a fixed
154 // buffer too small for it left the target empty and the connection never upgrading.
155 target_.resize(url_.path.size() + url_.query.size() + 1);
156 target_.resize(url_.request_target(target_));
157 }
158 ~Connection() { teardown(); }
159 Connection(const Connection&) = delete;
160 Connection& operator=(const Connection&) = delete;
162 // Idle -> Resolving. Reconnects happen automatically until close().
163 void connect() {
164 if (state_ != ConnState::Idle) return;
165 user_closed_ = false;
166 backoff_.reset();
167 start_resolve();
168 }
169
170 // Explicit shutdown: close frame on the live session, then Idle. No reconnect.
171 void close() {
172 if (state_ == ConnState::Idle) return;
173 user_closed_ = true;
174 set_state(ConnState::Closing);
175 if (active_ && active_->ws.is_open())
176 active_->ws.send_close(WsCloseCode::Normal, "client closing");
177 teardown();
178 set_state(ConnState::Idle);
179 }
180
181 // Sends go to the newest session (see rollover note above).
182 bool send_text(std::string_view text) noexcept {
183 Session* s = send_target();
184 if (s == nullptr || !s->ws.is_open()) return false;
185 const bool ok = s->ws.send_text(text);
186 if (!ok) ++stats_.drops;
187 return ok;
188 }
189 // Coalesces the send_text()/send_binary() calls up to uncork() into one write (WsClient::cork).
190 // uncork() returns false when the corked session failed meanwhile (true when none was open).
191 void cork() noexcept {
192 corked_ = send_target();
193 if (corked_ != nullptr) corked_->ws.cork();
194 }
195 bool uncork() noexcept {
196 Session* s = corked_;
197 corked_ = nullptr;
198 if (s == nullptr) return true;
199 if (s != active_.get() && s != pending_.get()) return false;
200 return s->ws.uncork();
201 }
202 bool send_binary(std::span<const std::byte> data) noexcept {
203 Session* s = send_target();
204 if (s == nullptr || !s->ws.is_open()) return false;
205 const bool ok = s->ws.send_binary(data);
206 if (!ok) ++stats_.drops;
207 return ok;
208 }
209 bool send_ping() noexcept {
210 Session* s = send_target();
211 return s != nullptr && s->ws.is_open() && s->ws.send_ping();
212 }
213
214 // Manual acknowledgement hooks (see ConnectionConfig::manual_*).
215 void auth_done() {
216 if (Session* s = newest(); s != nullptr && s->phase == Phase::Authenticating)
217 enter_subscribing(*s);
218 }
219 void subscribe_done() {
220 if (Session* s = newest(); s != nullptr && s->phase == Phase::Subscribing) enter_live(*s);
222
223 ConnState state() const noexcept { return state_; }
224 bool is_live() const noexcept { return state_ == ConnState::Live || state_ == ConnState::Stale; }
225 std::int64_t last_rx_ns() const noexcept { return last_rx_ns_; }
226 const Url& url() const noexcept { return url_; }
227 const ConnectionConfig& config() const noexcept { return cfg_; }
228 // The address the live (or connecting) session went to; nullopt without one.
229 std::optional<SockAddr> peer() const noexcept {
230 if (active_ == nullptr) return std::nullopt;
231 return active_->addr;
232 }
233 // The host's endpoint selection; nullptr when the connection does not select.
234 const std::shared_ptr<EndpointHost>& endpoints() const noexcept { return endpoints_; }
235
236 // Accumulated counters plus the live sessions' running totals.
237 ConnectionStats stats() const noexcept {
238 ConnectionStats s = stats_;
239 for (const Session* sess : {active_.get(), pending_.get()}) {
240 if (sess == nullptr) continue;
241 const WsStats& w = sess->ws.stats();
242 s.frames_rx += w.frames_rx;
243 s.frames_tx += w.frames_tx;
244 s.bytes_rx += w.bytes_rx;
245 s.bytes_tx += w.bytes_tx;
246 s.drops += w.drops;
247 }
248 return s;
249 }
250
251 private:
252 enum class Phase : std::uint8_t { Connecting, Authenticating, Subscribing, Live, Dead };
253
254 struct Session;
255
256 // WsClientHandler adapter. It is a separate, complete type because naming
257 // WsClient<Stream, Session> from inside Session would check the handler concept against an
258 // incomplete class.
259 struct SessionEvents {
260 Connection* owner;
261 Session* self;
262 void on_ws_progress(WsProgress p) { owner->on_session_progress(*self, p); }
263 void on_ws_open() { owner->on_session_open(*self); }
264 void on_ws_text(std::string_view t, std::int64_t ts) { owner->on_session_text(*self, t, ts); }
265 void on_ws_binary(std::span<const std::byte> b, std::int64_t ts) {
266 owner->on_session_binary(*self, b, ts);
267 }
268 void on_ws_ping(std::span<const std::byte>) { owner->touch_rx(); }
269 void on_ws_pong(std::span<const std::byte>) { owner->touch_rx(); }
270 void on_ws_close(std::uint16_t, std::string_view) { owner->on_session_end(*self); }
271 void on_ws_error(NetError, std::string_view) { owner->on_session_end(*self); }
272 };
273
274 // One WebSocket session; the Connection may briefly own two during rollover. Heap
275 // allocated and never moved, so the client's handler reference stays valid.
276 struct Session {
277 Session(Connection& c, Stream&& stream)
278 : events{&c, this}, ws(c.reactor_, std::move(stream), events, c.cfg_.ws) {}
279
280 SessionEvents events;
281 WsClient<Stream, SessionEvents> ws;
282 Phase phase = Phase::Connecting;
283 std::int64_t live_at_ns = 0;
284 SockAddr addr; // the peer it connected to
285 bool leased = false; // counted on addr by endpoints_ until retired
286 bool rollover = false;
287 EndpointChoice choice;
288 };
289
290 // ------------------------------------------------------------------------ state helpers
291 void set_state(ConnState s) {
292 if (state_ == s) return;
293 state_ = s;
294 handler_.on_state(s);
295 }
296 Session* newest() noexcept { return pending_ ? pending_.get() : active_.get(); }
297 Session* send_target() noexcept {
298 if (pending_ && pending_->phase != Phase::Connecting) return pending_.get();
299 return active_.get();
300 }
301 void touch_rx() noexcept { last_rx_ns_ = Reactor::now_ns(); }
302
303 // --------------------------------------------------------------------------- connecting
304 void start_resolve() {
305 set_state(ConnState::Resolving);
306 const std::uint64_t gen = ++resolve_gen_;
307 std::weak_ptr<int> alive = alive_;
308 auto done = [this, gen, alive](ResolveResult r) {
309 if (alive.expired() || gen != resolve_gen_ || user_closed_) return;
310 if (!r.ok()) {
311 schedule_backoff();
312 return;
313 }
314 addrs_ = std::move(r.addrs);
315 keep_reachable(cfg_.source, addrs_);
316 if (addrs_.empty()) {
317 schedule_backoff();
318 return;
319 }
320 addr_index_ = 0;
321 open_session(/*rollover=*/false);
322 };
323 if (endpoints_) {
324 resolver_.resolve(endpoints_, std::move(done));
325 } else {
326 resolver_.resolve(host_, url_.port, std::move(done));
327 }
328 }
329
330 Stream make_stream(TcpSocket&& sock) {
331 if constexpr (kTls) {
332 return Stream(*tls_, PlainStream(std::move(sock)), host_);
333 } else {
334 return Stream(std::move(sock));
335 }
336 }
337
338 void open_session(bool rollover) {
339 SockAddr addr;
340 EndpointChoice choice;
341 if (endpoints_) {
342 // Leased now, before the connect, so copies starting together spread out.
343 std::optional<EndpointChoice> c = endpoints_->acquire(/*lease=*/true);
344 choice = c ? *c : EndpointChoice{addrs_[addr_index_++ % addrs_.size()]};
345 addr = choice.addr;
346 } else {
347 addr = addrs_[addr_index_ % addrs_.size()];
348 ++addr_index_;
349 }
350 const bool leased = endpoints_ && choice.users > 0;
351 TcpSocket sock;
352 const std::optional<SockAddr> local = source_bind_address(cfg_.source, addr.family());
353 if (sock.connect(addr, local ? &*local : nullptr) == ConnectStatus::Error) {
354 if (endpoints_) {
355 endpoints_->failed(addr);
356 if (leased) endpoints_->release(addr);
357 }
358 if (rollover) {
359 schedule_rollover_retry();
360 } else {
361 schedule_backoff();
362 }
363 return;
364 }
365 sock.set_nodelay(true);
366 sock.set_keepalive(true);
367 sock.set_rcvbuf(4 * 1024 * 1024);
368 auto session = std::make_unique<Session>(*this, make_stream(std::move(sock)));
369 Session* raw = session.get();
370 raw->addr = addr;
371 raw->leased = leased;
372 raw->rollover = rollover;
373 raw->choice = choice;
374 (rollover ? pending_ : active_) = std::move(session);
375 if (!rollover) set_state(ConnState::Connecting);
376 arm_connect_timer();
377 const std::string headers = cfg_.make_headers ? cfg_.make_headers() : cfg_.extra_headers;
378 if (!raw->ws.start(host_, url_.port, kTls, target_, headers)) {
379 on_session_end(*raw);
380 }
381 }
382
383 void arm_connect_timer() {
384 cancel(connect_timer_);
385 connect_timer_ = reactor_.add_timer_after(ms_to_ns(cfg_.connect_timeout_ms), [this] {
386 connect_timer_ = kInvalidTimer;
387 if (Session* s = newest(); s != nullptr && s->phase != Phase::Live) on_session_end(*s);
388 });
389 }
390
391 void on_session_progress(Session& s, WsProgress p) {
392 if (&s != active_.get()) return; // rollover sessions do not change the public state
393 if (p == WsProgress::TcpConnected) {
394 if constexpr (kTls) set_state(ConnState::TlsHandshake);
395 } else {
396 set_state(ConnState::WsHandshake);
397 }
398 }
399
400 void on_session_open(Session& s) {
401 s.phase = Phase::Authenticating;
402 touch_rx();
403 if (&s == active_.get()) set_state(ConnState::Authenticating);
404 if (!cfg_.manual_auth) enter_subscribing(s);
405 }
406
407 void enter_subscribing(Session& s) {
408 s.phase = Phase::Subscribing;
409 if (&s == active_.get()) set_state(ConnState::Subscribing);
410 handler_.on_connected_send_subscriptions();
411 if (s.phase != Phase::Subscribing) return; // handler closed us
412 if (!cfg_.manual_subscribe) enter_live(s);
413 }
414
415 void enter_live(Session& s) {
416 s.phase = Phase::Live;
417 s.live_at_ns = Reactor::now_ns();
418 cancel(connect_timer_);
419 ++stats_.connects;
420 backoff_.reset();
421 if (&s == pending_.get()) promote_pending();
422 set_state(ConnState::Live);
423 arm_health_timer();
424 arm_heartbeat_timer();
425 arm_lifetime_timer();
426 if (endpoints_) {
427 log_endpoint_choice(s.rollover ? "ws rollover" : "ws", *endpoints_, s.choice);
428 endpoint_gen_ = endpoints_->generation();
429 arm_endpoint_timer();
430 }
431 }
432
433 // ------------------------------------------------------------------------------ traffic
434 void on_session_text(Session&, std::string_view t, std::int64_t ts) {
435 on_rx(ts);
436 handler_.on_text(t, ts);
437 }
438 void on_session_binary(Session&, std::span<const std::byte> b, std::int64_t ts) {
439 on_rx(ts);
440 handler_.on_binary(b, ts);
441 }
442 void on_rx(std::int64_t ts) {
443 last_rx_ns_ = ts;
444 if (state_ == ConnState::Stale) set_state(ConnState::Live);
445 }
446
447 // ------------------------------------------------------------------------------ failure
448 // Sessions end from inside their own WsClient callbacks, so they are parked in a
449 // graveyard and deleted from the reactor loop instead of synchronously.
450 void on_session_end(Session& s) {
451 if (s.phase == Phase::Dead) return;
452 // A session that never came up: its address is passed over by the next attempt.
453 if (endpoints_ && s.phase != Phase::Live && !user_closed_) endpoints_->failed(s.addr);
454 s.phase = Phase::Dead;
455 retire(s);
456 if (&s == pending_.get()) {
457 // A failed rollover keeps the old session; try again after a backoff delay.
458 bury(pending_);
459 schedule_rollover_retry();
460 return;
461 }
462 bury(active_);
463 if (pending_) {
464 // The old session died while the new one was still connecting: the new one becomes
465 // the (not yet live) active session and the public state follows it.
466 active_ = std::move(pending_);
467 set_state(active_->phase == Phase::Connecting ? ConnState::Connecting
468 : active_->phase == Phase::Authenticating ? ConnState::Authenticating
470 return;
471 }
472 cancel_session_timers();
473 if (!user_closed_) schedule_backoff();
474 }
475
476 void retire(Session& s) noexcept {
477 const WsStats& w = s.ws.stats();
478 stats_.frames_rx += w.frames_rx;
479 stats_.frames_tx += w.frames_tx;
480 stats_.bytes_rx += w.bytes_rx;
481 stats_.bytes_tx += w.bytes_tx;
482 stats_.drops += w.drops;
483 s.ws.close();
484 if (s.leased) {
485 s.leased = false;
486 endpoints_->release(s.addr);
487 }
488 }
489
490 void schedule_backoff() {
491 ++stats_.reconnects;
492 set_state(ConnState::Backoff);
493 cancel(backoff_timer_);
494 backoff_timer_ = reactor_.add_timer_after(ms_to_ns(backoff_.next_ms()), [this] {
495 backoff_timer_ = kInvalidTimer;
496 if (!user_closed_) start_resolve();
497 });
498 }
499
500 // ----------------------------------------------------------------------------- timers
501 void arm_health_timer() {
502 cancel(health_timer_);
503 const std::uint32_t period =
504 std::max<std::uint32_t>(10, std::min(cfg_.stale_ms, cfg_.dead_ms) / 4);
505 health_timer_ = reactor_.add_timer_after(ms_to_ns(period), [this] {
506 health_timer_ = kInvalidTimer;
507 if (!is_live()) return;
508 const std::int64_t idle_ms = (Reactor::now_ns() - last_rx_ns_) / 1'000'000;
509 if (idle_ms >= cfg_.dead_ms) {
510 ++stats_.dead_events;
511 on_session_end(*active_); // forced reconnect through Backoff
512 return;
513 }
514 if (idle_ms >= cfg_.stale_ms && state_ == ConnState::Live) {
515 ++stats_.stale_events;
516 set_state(ConnState::Stale);
517 }
518 arm_health_timer();
519 });
520 }
521
522 void arm_heartbeat_timer() {
523 cancel(heartbeat_timer_);
524 if (cfg_.heartbeat_interval_ms == 0) return;
525 heartbeat_timer_ = reactor_.add_timer_after(ms_to_ns(cfg_.heartbeat_interval_ms), [this] {
526 heartbeat_timer_ = kInvalidTimer;
527 if (!is_live()) return;
528 send_ping();
529 arm_heartbeat_timer();
530 });
531 }
532
533 void arm_lifetime_timer() {
534 cancel(lifetime_timer_);
535 if (cfg_.max_lifetime_ms == 0) return;
536 lifetime_timer_ = reactor_.add_timer_after(ms_to_ns(cfg_.max_lifetime_ms), [this] {
537 lifetime_timer_ = kInvalidTimer;
538 start_rollover();
539 });
540 }
541
542 // A connection that can roll over looks at its host's probes when they change, and moves when
543 // its address has fallen switch_us behind the fastest or left the lookups.
544 void arm_endpoint_timer() {
545 cancel(endpoint_timer_);
546 if (cfg_.max_lifetime_ms == 0) return;
547 const EndpointSelectConfig& ec = endpoints_->config();
548 if (ec.move_check_ms == 0) return;
549 endpoint_timer_ = reactor_.add_timer_after(ms_to_ns(ec.move_check_ms), [this] {
550 endpoint_timer_ = kInvalidTimer;
551 if (!is_live()) return;
552 if (const std::uint64_t g = endpoints_->generation(); g != endpoint_gen_ && !pending_) {
553 endpoint_gen_ = g;
554 if (endpoints_->should_move(active_->addr)) {
555 ++stats_.endpoint_moves;
556 start_rollover();
557 }
558 }
559 arm_endpoint_timer();
560 });
561 }
562
563 void start_rollover() {
564 if (!is_live() || pending_ || addrs_.empty()) return;
565 ++stats_.rollovers;
566 open_session(/*rollover=*/true);
567 }
568
569 void schedule_rollover_retry() {
570 cancel(lifetime_timer_);
571 lifetime_timer_ = reactor_.add_timer_after(ms_to_ns(backoff_.next_ms()), [this] {
572 lifetime_timer_ = kInvalidTimer;
573 start_rollover();
574 });
575 }
576
577 void promote_pending() {
578 if (active_) {
579 retire(*active_);
580 bury(active_);
581 }
582 active_ = std::move(pending_);
583 }
584
585 void bury(std::unique_ptr<Session>& s) {
586 if (!s) return;
587 graveyard_.push_back(std::move(s));
588 if (reap_pending_) return;
589 reap_pending_ = true;
590 std::weak_ptr<int> alive = alive_;
591 reactor_.post([this, alive] {
592 if (alive.expired()) return;
593 reap_pending_ = false;
594 graveyard_.clear();
595 });
596 }
597
598 void cancel(TimerId& id) noexcept {
599 if (id != kInvalidTimer) {
600 reactor_.cancel_timer(id);
601 id = kInvalidTimer;
602 }
603 }
604 void cancel_session_timers() noexcept {
605 cancel(connect_timer_);
606 cancel(health_timer_);
607 cancel(heartbeat_timer_);
608 cancel(lifetime_timer_);
609 cancel(endpoint_timer_);
610 }
611 // close(): sessions go to the graveyard (we may be inside one of their callbacks).
612 // Destructor: everything is deleted now; destroying a Connection from inside its own
613 // handler callbacks is not supported.
614 void teardown() noexcept {
615 cancel_session_timers();
616 cancel(backoff_timer_);
617 ++resolve_gen_; // orphan any in-flight resolve
618 if (pending_) {
619 retire(*pending_);
620 bury(pending_);
621 }
622 if (active_) {
623 retire(*active_);
624 bury(active_);
625 }
626 }
627 static constexpr std::int64_t ms_to_ns(std::uint64_t ms) noexcept {
628 return static_cast<std::int64_t>(ms) * 1'000'000;
629 }
630
631 Reactor& reactor_;
632 ConnectionConfig cfg_;
633 Handler& handler_;
634 Url url_;
635 std::string host_;
636 std::string target_;
637 std::shared_ptr<const TlsContext> shared_tls_;
638 const TlsContext* tls_ = nullptr;
639 ExponentialBackoff backoff_;
640 AsyncResolver resolver_;
641 std::shared_ptr<int> alive_ = std::make_shared<int>(0);
642 std::uint64_t resolve_gen_ = 0;
643 std::vector<SockAddr> addrs_;
644 std::size_t addr_index_ = 0;
645 std::shared_ptr<EndpointHost> endpoints_; // set: endpoint selection
646 std::uint64_t endpoint_gen_ = 0; // the host's generation last looked at
647 std::unique_ptr<Session> active_;
648 std::unique_ptr<Session> pending_;
649 Session* corked_ = nullptr; // between cork() and uncork()
650 std::vector<std::unique_ptr<Session>> graveyard_;
651 bool reap_pending_ = false;
652 ConnState state_ = ConnState::Idle;
653 bool user_closed_ = false;
654 std::int64_t last_rx_ns_ = 0;
655 ConnectionStats stats_;
656 TimerId connect_timer_ = kInvalidTimer;
657 TimerId health_timer_ = kInvalidTimer;
658 TimerId heartbeat_timer_ = kInvalidTimer;
659 TimerId lifetime_timer_ = kInvalidTimer;
660 TimerId backoff_timer_ = kInvalidTimer;
661 TimerId endpoint_timer_ = kInvalidTimer;
662};
663
664} // namespace fastmm::net
Exponential backoff with jitter for reconnects: delay_n = cap_n * (1 - jitter) + U(0,...
Definition connection.hpp:127
const Url & url() const noexcept
Definition connection.hpp:228
void close()
Explicit shutdown: close frame on the live session, then Idle. No reconnect.
Definition connection.hpp:173
void cork() noexcept
Coalesces the send_text()/send_binary() calls up to uncork() into one write (WsClient::cork).
Definition connection.hpp:193
std::int64_t last_rx_ns() const noexcept
Definition connection.hpp:227
ConnectionStats stats() const noexcept
Accumulated counters plus the live sessions' running totals.
Definition connection.hpp:239
bool uncork() noexcept
Definition connection.hpp:197
const ConnectionConfig & config() const noexcept
Definition connection.hpp:229
ConnState state() const noexcept
Definition connection.hpp:225
bool send_text(std::string_view text) noexcept
Sends go to the newest session (see rollover note above).
Definition connection.hpp:184
const std::shared_ptr< EndpointHost > & endpoints() const noexcept
The host's endpoint selection; nullptr when the connection does not select.
Definition connection.hpp:236
std::optional< SockAddr > peer() const noexcept
The address the live (or connecting) session went to; nullopt without one.
Definition connection.hpp:231
bool is_live() const noexcept
Definition connection.hpp:226
Connection & operator=(const Connection &)=delete
void auth_done()
Manual acknowledgement hooks (see ConnectionConfig::manual_*).
Definition connection.hpp:217
void connect()
Idle -> Resolving. Reconnects happen automatically until close().
Definition connection.hpp:165
void subscribe_done()
Definition connection.hpp:221
~Connection()
Definition connection.hpp:160
bool send_binary(std::span< const std::byte > data) noexcept
Definition connection.hpp:204
bool send_ping() noexcept
Definition connection.hpp:211
std::uint32_t next_ms() noexcept
Delay for the current attempt in milliseconds; advances the attempt counter.
Definition backoff.hpp:48
void reset() noexcept
Definition backoff.hpp:58
Definition reactor.hpp:72
TimerId add_timer_after(std::int64_t delay_ns, TimerCallback cb)
Definition reactor.hpp:105
static std::int64_t now_ns() noexcept
CLOCK_MONOTONIC.
Definition connection.hpp:104
Definition reactor.hpp:37
WsProgress
Milestones before the upgrade completes, so owners can report fine-grained states.
Definition ws_client.hpp:35
@ TcpConnected
TCP established (TLS handshake starts next for TLS streams)
ConnState
Definition connection.hpp:55
@ Stale
Live, but nothing received for stale_ms (sub-state of Live)
std::uint64_t TimerId
Definition reactor.hpp:69
std::string_view to_string(ReactorBackend backend) noexcept
"epoll" / "io_uring", the spelling of [engine] net_backend.
void validate_connection_config(const ConnectionConfig &cfg, Url &url)
Throws std::invalid_argument on a bad URL; fills url (views into cfg.url).
constexpr TimerId kInvalidTimer
Definition reactor.hpp:70
ConnState
Definition enums.hpp:453
Single-threaded event loop with a timer min-heap and a thread-safe mailbox (post/wake via eventfd),...
Definition backoff.hpp:32
Definition connection.hpp:73
bool insecure
skip verification entirely
Definition connection.hpp:75
std::string ca_file
trust only this bundle (self-signed sim server)
Definition connection.hpp:74
Definition connection.hpp:71
std::uint32_t stale_ms
Definition connection.hpp:77
bool manual_subscribe
handler calls subscribe_done()
Definition connection.hpp:90
bool manual_auth
handler calls auth_done()
Definition connection.hpp:89
BackoffConfig backoff
Definition connection.hpp:79
std::string url
ws:// or wss://host[:port]/path?query
Definition connection.hpp:72
std::uint32_t heartbeat_interval_ms
0 = no client pings
Definition connection.hpp:81
SourceAddress source
Where the connection leaves this host from (net/source_address.hpp); empty: anywhere.
Definition connection.hpp:85
std::string extra_headers
"Name: value\\r\\n" block for the upgrade request
Definition connection.hpp:91
std::uint64_t max_lifetime_ms
0 = never roll over
Definition connection.hpp:80
std::uint32_t connect_timeout_ms
Definition connection.hpp:82
WsClientConfig ws
Venue handlers parse text with simdjson, whose first stage rejects invalid UTF-8; the WebSocket-level...
Definition connection.hpp:97
std::function< std::string()> make_headers
Called before every upgrade request and used instead of extra_headers when set: headers signed with a...
Definition connection.hpp:94
std::optional< bool > select_endpoint
Endpoint selection for this connection: true or false, or nullopt for the process's default (Endpoint...
Definition connection.hpp:88
struct fastmm::net::ConnectionConfig::Tls tls
std::uint32_t dead_ms
Definition connection.hpp:78
Definition connection.hpp:112
std::uint64_t drops
Definition connection.hpp:122
std::uint64_t frames_tx
Definition connection.hpp:119
std::uint64_t bytes_rx
Definition connection.hpp:120
std::uint64_t connects
sessions that reached Live
Definition connection.hpp:113
std::uint64_t endpoint_moves
rollovers to a faster address (endpoint selection)
Definition connection.hpp:123
std::uint64_t reconnects
Backoff entries.
Definition connection.hpp:114
std::uint64_t bytes_tx
Definition connection.hpp:121
std::uint64_t frames_rx
Definition connection.hpp:118
std::uint64_t rollovers
Definition connection.hpp:115
std::uint64_t stale_events
Definition connection.hpp:116
std::uint64_t dead_events
Definition connection.hpp:117
Definition url.hpp:16
std::uint16_t port
explicit or scheme default (80/443)
Definition url.hpp:19
std::size_t request_target(std::span< char > buf) const noexcept
Path + "?" + query as sent in the request line; buf must hold both.
Definition url.hpp:25
std::string_view host
without brackets for IPv6 literals
Definition url.hpp:18
std::string_view query
without '?'
Definition url.hpp:21
std::string_view path
always at least "/"
Definition url.hpp:20
Definition ws_client.hpp:58
bool validate_utf8
reject text messages that are not UTF-8 (close code 1007)
Definition ws_client.hpp:63
Definition ws_client.hpp:66
std::uint64_t drops
sends refused because the send buffer was full
Definition ws_client.hpp:71
std::uint64_t frames_tx
Definition ws_client.hpp:68
std::uint64_t frames_rx
Definition ws_client.hpp:67
std::uint64_t bytes_tx
Definition ws_client.hpp:70
std::uint64_t bytes_rx
Definition ws_client.hpp:69
Minimal URL parsing / query building for venue endpoints.
RFC 6455 WebSocket client over any ByteStream, driven by a Reactor.