CARLA
Loading...
Searching...
No Matches
ServerSession.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
9
10#include "carla/Debug.h"
11#include "carla/Logging.h"
12
13#include <boost/asio/read.hpp>
14#include <boost/asio/write.hpp>
15#include <boost/asio/bind_executor.hpp>
16#include <boost/asio/post.hpp>
17
18#include <atomic>
19#include <chrono>
20#include <thread>
21
22namespace carla {
23namespace streaming {
24namespace detail {
25namespace tcp {
26
27 static std::atomic_size_t SESSION_COUNTER{0u};
28
30 boost::asio::io_context &io_context,
31 const time_duration timeout,
32 Server &server)
34 std::string("tcp server session ") + std::to_string(SESSION_COUNTER)),
35 _server(server),
37 _socket(io_context),
38 _timeout(timeout),
39 _deadline(io_context, std::chrono::steady_clock::time_point::max()),
40 _strand(io_context) {}
41
43 callback_function_type on_opened,
44 callback_function_type on_closed) {
45 DEBUG_ASSERT(on_opened && on_closed);
46 _on_closed = std::move(on_closed);
47
48 // This forces not using Nagle's algorithm.
49 // Improves the sync mode velocity on Linux by a factor of ~3.
50 const boost::asio::ip::tcp::no_delay option(true);
51 _socket.set_option(option);
52
53 StartTimer();
54 auto self = shared_from_this(); // To keep myself alive.
55 boost::asio::post(_strand, [=]() {
56
57 auto handle_query = [this, self, callback=std::move(on_opened)](
58 const boost::system::error_code &ec,
59 size_t DEBUG_ONLY(bytes_received)) {
60 if (!ec) {
61 DEBUG_ASSERT_EQ(bytes_received, sizeof(_stream_id));
62 log_debug("session", _session_id, "for stream", _stream_id, " started");
63 boost::asio::post(_strand.context(), [=]() { callback(self); });
64 } else {
65 log_error("session", _session_id, ": error retrieving stream id :", ec.message());
66 CloseNow(ec);
67 }
68 };
69
70 // Read the stream id.
71 _deadline.expires_after(_timeout.to_chrono());
72 boost::asio::async_read(
73 _socket,
74 boost::asio::buffer(&_stream_id, sizeof(_stream_id)),
75 boost::asio::bind_executor(_strand, handle_query));
76 });
77 }
78
79 void ServerSession::Write(std::shared_ptr<const Message> message) {
80 DEBUG_ASSERT(message != nullptr);
81 DEBUG_ASSERT(!message->empty());
82 auto self = shared_from_this();
83 if (!_socket.is_open()) {
84 return;
85 }
86 if (_is_writing) {
88 // Wait until the previous message has been sent, but not forever: the
89 // caller is the game thread or the render thread, and a client that
90 // stops reading this socket (a listen() callback that never returns,
91 // a frozen process) would otherwise stall the whole server, every
92 // other client included (#10233). Drop that client instead; its
93 // streaming client reconnects on its own.
94 const auto start = std::chrono::steady_clock::now();
95 const auto limit = _timeout.to_chrono();
96 bool warned = false;
97 while (_is_writing) {
98 std::this_thread::sleep_for(std::chrono::microseconds(100));
99 const auto waited = std::chrono::steady_clock::now() - start;
100 if (!warned && waited > std::chrono::seconds(1)) {
101 warned = true;
102 log_warning("streaming session", _session_id, "for stream", _stream_id,
103 ": client is not reading, synchronous send blocked for 1 s");
104 }
105 if (waited > limit) {
106 log_error("streaming session", _session_id, "for stream", _stream_id,
107 ": client did not read for", _timeout.milliseconds(),
108 "ms in synchronous mode, closing the session and dropping the message");
109 Close();
110 return;
111 }
112 }
113 } else {
114 // ignore this message
115 log_debug("session", _session_id, ": connection too slow: message discarded");
116 return;
117 }
118 }
119 _is_writing = true;
120
121 auto handle_sent = [this, self, message](const boost::system::error_code &ec, size_t DEBUG_ONLY(bytes)) {
122 _is_writing = false;
123 if (ec) {
124 log_info("session", _session_id, ": error sending data :", ec.message());
125 CloseNow(ec);
126 } else {
127 DEBUG_ONLY(log_debug("session", _session_id, ": successfully sent", bytes, "bytes"));
128 DEBUG_ASSERT_EQ(bytes, sizeof(message_size_type) + message->size());
129 }
130 };
131
132 log_debug("session", _session_id, ": sending message of", message->size(), "bytes");
133
134 // Start the write on the session's strand: the socket and the timer are
135 // not thread-safe, and CloseNow() runs on the strand.
136 boost::asio::post(_strand, [this, self, message, handle_sent]() mutable {
137 if (_is_closed || !_socket.is_open()) {
138 _is_writing = false;
139 return;
140 }
141 _deadline.expires_after(_timeout.to_chrono());
142 boost::asio::async_write(_socket, message->GetBufferSequence(),
143 boost::asio::bind_executor(_strand, std::move(handle_sent)));
144 });
145 }
146
148 boost::asio::post(_strand, [self=shared_from_this()]() { self->CloseNow(); });
149 }
150
152 if (_deadline.expiry() <= std::chrono::steady_clock::now()) {
153 log_debug("session", _session_id, "timed out");
154 Close();
155 } else {
156 _deadline.async_wait([this, self=shared_from_this()](boost::system::error_code ec) {
157 if (!ec) {
158 StartTimer();
159 } else {
160 log_debug("session", _session_id, "timed out error:", ec.message());
161 }
162 });
163 }
164 }
165
166 void ServerSession::CloseNow(boost::system::error_code ec) {
167 if (_is_closed.exchange(true)) return;
168 _deadline.cancel();
169 if (!ec)
170 {
171 if (_socket.is_open()) {
172 boost::system::error_code ec2;
173 _socket.shutdown(boost::asio::socket_base::shutdown_both, ec2);
174 _socket.close();
175 }
176 }
177 _on_closed(shared_from_this());
178 log_debug("session", _session_id, "closed");
179 }
180
181} // namespace tcp
182} // namespace detail
183} // namespace streaming
184} // namespace carla
#define DEBUG_ASSERT(predicate)
Definition Debug.h:66
#define DEBUG_ASSERT_EQ(lhs, rhs)
Definition Debug.h:76
#define DEBUG_ONLY(code)
Definition Debug.h:55
#define LIBCARLA_INITIALIZE_LIFETIME_PROFILER(display_name)
void CloseNow(boost::system::error_code ec=boost::system::error_code())
void Close()
Post a job to close the session.
ServerSession(boost::asio::io_context &io_context, time_duration timeout, Server &server)
void Open(callback_function_type on_opened, callback_function_type on_closed)
Starts the session and calls on_opened after successfully reading the stream id, and on_closed once t...
boost::asio::io_context::strand _strand
std::atomic_bool _is_writing
Set by the sending thread, cleared by the write handler on the strand.
std::function< void(std::shared_ptr< ServerSession >)> callback_function_type
void Write(std::shared_ptr< const Message > message)
Writes some data to the socket.
Positive time duration up to milliseconds resolution.
Definition Time.h:20
static time_duration milliseconds(size_t timeout)
Definition Time.h:27
constexpr auto to_chrono() const
Definition Time.h:54
static std::atomic_size_t SESSION_COUNTER
This file contains definitions of common data structures used in traffic manager.