127 static_assert(std::is_same_v<Stream, PlainStream> || kTls,
128 "Connection supports PlainStream and TlsStream<PlainStream>");
136 const TlsContext* tls =
nullptr)
138 cfg_(std::move(cfg)),
140 backoff_(cfg_.backoff),
143 if constexpr (kTls) {
144 if (tls ==
nullptr) {
146 tls = shared_tls_.get();
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);
155 target_.resize(url_.
path.size() + url_.
query.size() + 1);
159 Connection(
const Connection&) =
delete;
165 user_closed_ =
false;
175 if (active_ && active_->ws.is_open())
176 active_->ws.send_close(WsCloseCode::Normal,
"client closing");
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;
191 void cork() noexcept {
192 corked_ = send_target();
193 if (corked_ !=
nullptr) corked_->ws.cork();
196 Session* s = corked_;
198 if (s ==
nullptr)
return true;
199 if (s != active_.get() && s != pending_.get())
return false;
200 return s->ws.uncork();
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;
210 Session* s = send_target();
211 return s !=
nullptr && s->ws.is_open() && s->ws.send_ping();
216 if (Session* s = newest(); s !=
nullptr && s->phase == Phase::Authenticating)
217 enter_subscribing(*s);
220 if (Session* s = newest(); s !=
nullptr && s->phase == Phase::Subscribing) enter_live(*s);
225 std::int64_t
last_rx_ns() const noexcept {
return last_rx_ns_; }
226 const Url&
url() const noexcept {
return url_; }
229 std::optional<SockAddr>
peer() const noexcept {
230 if (active_ ==
nullptr)
return std::nullopt;
231 return active_->addr;
234 const std::shared_ptr<EndpointHost>&
endpoints() const noexcept {
return endpoints_; }
239 for (
const Session* sess : {active_.get(), pending_.get()}) {
240 if (sess ==
nullptr)
continue;
241 const WsStats& w = sess->ws.stats();
252 enum class Phase : std::uint8_t { Connecting, Authenticating, Subscribing, Live, Dead };
259 struct SessionEvents {
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);
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); }
277 Session(Connection& c, Stream&& stream)
278 : events{&c, this}, ws(c.reactor_, std::move(stream), events, c.cfg_.ws) {}
280 SessionEvents events;
281 WsClient<Stream, SessionEvents> ws;
282 Phase phase = Phase::Connecting;
283 std::int64_t live_at_ns = 0;
286 bool rollover =
false;
287 EndpointChoice choice;
292 if (state_ == s)
return;
294 handler_.on_state(s);
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();
304 void start_resolve() {
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;
314 addrs_ = std::move(r.addrs);
315 keep_reachable(cfg_.
source, addrs_);
316 if (addrs_.empty()) {
324 resolver_.resolve(endpoints_, std::move(done));
326 resolver_.resolve(host_, url_.
port, std::move(done));
330 Stream make_stream(TcpSocket&& sock) {
331 if constexpr (kTls) {
332 return Stream(*tls_, PlainStream(std::move(sock)), host_);
334 return Stream(std::move(sock));
338 void open_session(
bool rollover) {
340 EndpointChoice choice;
343 std::optional<EndpointChoice> c = endpoints_->acquire(
true);
344 choice = c ? *c : EndpointChoice{addrs_[addr_index_++ % addrs_.size()]};
347 addr = addrs_[addr_index_ % addrs_.size()];
350 const bool leased = endpoints_ && choice.users > 0;
352 const std::optional<SockAddr> local = source_bind_address(cfg_.
source, addr.family());
353 if (sock.connect(addr, local ? &*local : nullptr) == ConnectStatus::
Error) {
355 endpoints_->failed(addr);
356 if (leased) endpoints_->release(addr);
359 schedule_rollover_retry();
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();
371 raw->leased = leased;
372 raw->rollover = rollover;
373 raw->choice = choice;
374 (rollover ? pending_ : active_) = std::move(session);
378 if (!raw->ws.start(host_, url_.
port, kTls, target_, headers)) {
379 on_session_end(*raw);
383 void arm_connect_timer() {
384 cancel(connect_timer_);
386 connect_timer_ = kInvalidTimer;
387 if (Session* s = newest(); s != nullptr && s->phase != Phase::Live) on_session_end(*s);
391 void on_session_progress(Session& s,
WsProgress p) {
392 if (&s != active_.get())
return;
400 void on_session_open(Session& s) {
401 s.phase = Phase::Authenticating;
407 void enter_subscribing(Session& s) {
408 s.phase = Phase::Subscribing;
410 handler_.on_connected_send_subscriptions();
411 if (s.phase != Phase::Subscribing)
return;
415 void enter_live(Session& s) {
416 s.phase = Phase::Live;
418 cancel(connect_timer_);
421 if (&s == pending_.get()) promote_pending();
424 arm_heartbeat_timer();
425 arm_lifetime_timer();
427 log_endpoint_choice(s.rollover ?
"ws rollover" :
"ws", *endpoints_, s.choice);
428 endpoint_gen_ = endpoints_->generation();
429 arm_endpoint_timer();
434 void on_session_text(Session&, std::string_view t, std::int64_t ts) {
436 handler_.on_text(t, ts);
438 void on_session_binary(Session&, std::span<const std::byte> b, std::int64_t ts) {
440 handler_.on_binary(b, ts);
442 void on_rx(std::int64_t ts) {
450 void on_session_end(Session& s) {
451 if (s.phase == Phase::Dead)
return;
453 if (endpoints_ && s.phase != Phase::Live && !user_closed_) endpoints_->failed(s.addr);
454 s.phase = Phase::Dead;
456 if (&s == pending_.get()) {
459 schedule_rollover_retry();
466 active_ = std::move(pending_);
472 cancel_session_timers();
473 if (!user_closed_) schedule_backoff();
476 void retire(Session& s)
noexcept {
477 const WsStats& w = s.ws.stats();
482 stats_.
drops += w.drops;
486 endpoints_->release(s.addr);
490 void schedule_backoff() {
493 cancel(backoff_timer_);
495 backoff_timer_ = kInvalidTimer;
496 if (!user_closed_) start_resolve();
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);
508 const std::int64_t idle_ms = (
Reactor::now_ns() - last_rx_ns_) / 1'000'000;
511 on_session_end(*active_);
522 void arm_heartbeat_timer() {
523 cancel(heartbeat_timer_);
526 heartbeat_timer_ = kInvalidTimer;
527 if (!is_live()) return;
529 arm_heartbeat_timer();
533 void arm_lifetime_timer() {
534 cancel(lifetime_timer_);
537 lifetime_timer_ = kInvalidTimer;
544 void arm_endpoint_timer() {
545 cancel(endpoint_timer_);
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_) {
554 if (endpoints_->should_move(active_->addr)) {
555 ++stats_.endpoint_moves;
559 arm_endpoint_timer();
563 void start_rollover() {
564 if (!is_live() || pending_ || addrs_.empty())
return;
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;
577 void promote_pending() {
582 active_ = std::move(pending_);
585 void bury(std::unique_ptr<Session>& s) {
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;
598 void cancel(
TimerId&
id)
noexcept {
600 reactor_.cancel_timer(
id);
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_);
614 void teardown() noexcept {
615 cancel_session_timers();
616 cancel(backoff_timer_);
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;
632 ConnectionConfig cfg_;
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_;
646 std::uint64_t endpoint_gen_ = 0;
647 std::unique_ptr<Session> active_;
648 std::unique_ptr<Session> pending_;
649 Session* corked_ =
nullptr;
650 std::vector<std::unique_ptr<Session>> graveyard_;
651 bool reap_pending_ =
false;
653 bool user_closed_ =
false;
654 std::int64_t last_rx_ns_ = 0;
655 ConnectionStats stats_;