Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,9 @@ public static class Client {

/** Resource not found. */
public static final int RESOURCE_NOT_FOUND_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 10);

/** Client operation timeout. */
public static final int CLIENT_OPERATION_TIMEOUT_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 11);
}

/** SQL error group. */
Expand Down
1 change: 1 addition & 0 deletions modules/platforms/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ if (${ENABLE_TESTS})

if (${ENABLE_CLIENT})
add_subdirectory(tests/client-test)
add_subdirectory(tests/fake_server)
endif()

if (${ENABLE_ODBC})
Expand Down
52 changes: 48 additions & 4 deletions modules/platforms/cpp/ignite/client/detail/node_connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ node_connection::node_connection(std::uint64_t id, std::shared_ptr<network::asyn
, m_timer_thread(std::move(timer_thread)){}

node_connection::~node_connection() {
for (auto &handler : m_request_handlers) {
for (auto& req : m_request_handlers) {
auto handling_res = result_of_operation<void>([&]() {
auto res = handler.second->set_error(ignite_error("Connection closed before response was received"));
auto handler = req.second.handler;
auto res = handler->set_error(ignite_error("Connection closed before response was received"));
if (res.has_error())
m_logger->log_error(
"Uncaught user callback exception while handling operation error: " + res.error().what_str());
Expand Down Expand Up @@ -182,6 +183,10 @@ ignite_result<void> node_connection::process_handshake_rsp(bytes_view msg) {
plan_heartbeat(m_heartbeat_interval);
}

if (m_configuration.get_operation_timeout().count() > 0) {
handle_timeouts();
}

return {};
}

Expand All @@ -192,7 +197,7 @@ std::shared_ptr<response_handler> node_connection::get_and_remove_handler(std::i
if (it == m_request_handlers.end())
return {};

auto res = std::move(it->second);
auto res = std::move(it->second.handler);
m_request_handlers.erase(it);

return res;
Expand All @@ -203,7 +208,46 @@ std::shared_ptr<response_handler> node_connection::find_handler_unsafe(std::int6
if (it == m_request_handlers.end())
return {};

return it->second;
return it->second.handler;
}

void node_connection::handle_timeouts() {
auto now = std::chrono::steady_clock::now();

{
std::lock_guard lock(m_request_handlers_mutex);

std::vector<int64_t> keys_for_erasure;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's try avoiding additional memory allocation here. Let's erase values as we move through the map. We hold the lock anyway. It can be done with iterator:

auto it = map.begin();
while (it != map.end()) {
  if (something) {
    it = map.erase(it);
    continue;
  }
  ++it;
}


for (auto& [id, req] : m_request_handlers) {
if (req.timeouts_at > now) {
Copy link

Copilot AI Nov 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comparison logic is inverted. This should be req.timeouts_at < now to check if the request has timed out (i.e., the timeout time point is in the past). Currently, it marks requests as timed out when they haven't expired yet.

Suggested change
if (req.timeouts_at > now) {
if (req.timeouts_at < now) {

Copilot uses AI. Check for mistakes.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems wrong. Do tests pass?

Suggested change
if (req.timeouts_at > now) {
if (req.timeouts_at < now) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will add a test which would fail with suc incorrect code. Thats left as artifact of refactoring.


std::stringstream ss;
ss << "Operation timeout [req_id=" << id << "]";
auto res = req.handler->set_error(ignite_error(error::code::CLIENT_OPERATION_TIMEOUT,ss.str()));
Copy link

Copilot AI Nov 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing space after comma in function call. Should be ss.str())ss.str()) with proper spacing: CLIENT_OPERATION_TIMEOUT, ss.str().

Suggested change
auto res = req.handler->set_error(ignite_error(error::code::CLIENT_OPERATION_TIMEOUT,ss.str()));
auto res = req.handler->set_error(ignite_error(error::code::CLIENT_OPERATION_TIMEOUT, ss.str()));

Copilot uses AI. Check for mistakes.
Comment on lines +225 to +227
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also log it as a warning here.


keys_for_erasure.push_back(id);

if (res.has_error())
this->m_logger->log_error(
"Uncaught user callback exception while handling operation error: " + res.error().what_str());
}
}

for (int64_t key : keys_for_erasure) {
m_request_handlers.erase(key);
}
}

if (auto timeout = m_configuration.get_operation_timeout(); timeout.count() > 0) {
if (auto timer_thread = m_timer_thread.lock()) {
timer_thread->add(timeout, [self_weak = weak_from_this()] {
if (auto self = self_weak.lock()) {
self->handle_timeouts();
}
});
}
}
}

} // namespace ignite::detail
43 changes: 37 additions & 6 deletions modules/platforms/cpp/ignite/client/detail/node_connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
public:
typedef std::function<void(protocol::writer&, const protocol::protocol_context&)> writer_function_type;

struct pending_request {
/** Handler function for request */
std::shared_ptr<response_handler> handler = nullptr;

/**
* Optional request timeout.
* When provided contains time point after which request would be considered as timed out.
*/
std::optional<std::chrono::time_point<std::chrono::steady_clock>> timeouts_at = std::nullopt;

explicit pending_request(
std::shared_ptr<response_handler> handler,
std::optional<std::chrono::time_point<std::chrono::steady_clock>> timeouts_at)
: handler(std::move(handler))
, timeouts_at(timeouts_at) {}
};

// Deleted
node_connection() = delete;
node_connection(node_connection &&) = delete;
Expand Down Expand Up @@ -103,8 +120,11 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
* @param handler response handler.
* @return A request ID on success and @c std::nullopt otherwise.
*/
[[nodiscard]] std::optional<std::int64_t> perform_request(protocol::client_operation op, const writer_function_type &wr,
std::shared_ptr<response_handler> handler) {
[[nodiscard]] std::optional<std::int64_t> perform_request(
protocol::client_operation op,
const writer_function_type &wr,
std::shared_ptr<response_handler> handler)
{
auto req_id = generate_request_id();
std::vector<std::byte> message;
{
Expand All @@ -119,9 +139,14 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
buffer.write_length_header();
}

std::optional<std::chrono::time_point<std::chrono::steady_clock>> timeout{};
if (m_configuration.get_operation_timeout().count() > 0) {
timeout = std::chrono::steady_clock::now() + m_configuration.get_operation_timeout();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In java client there is an optimization for calling analog of ::now(). I am not aware of performance of this method. Should we research if similiar optimisation is required?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? What exactly should be optimized here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TLDR:
I was under impression that java's System.currentTimeMillis() and steady_clock::now() have similar implementation and drawbacks. But learning a bit deeper revealed to me that system_clock::now() should be analogous to System.currentTimeMillis().


as I said I don't know any performance issues of this method. In java case there were some issues with analogous System.currentTimeMillis() on windows platform. That could be a reason why in ignite codebase we have org.apache.ignite.internal.util.FastTimestamps#coarseCurrentTimeMillis.

what optimization could be (if calling std::chrono::steady_clock::now() would be slower than we can afford). We spawn a thread which updates atomic value every X seconds. Instead of calling ::now() we read from atomic variable. As I googled a bit calling steady_clock::now() doesn't switch context from userspace to kernelspace (on opposing of calling system_clock::now()).

I am pretty sure that we don't want to do it right now, but maybe small task to research performance impact of calling ::now on each request.

}

{
std::lock_guard<std::recursive_mutex> lock(m_request_handlers_mutex);
m_request_handlers[req_id] = std::move(handler);
m_request_handlers.emplace(req_id, pending_request(std::move(handler), timeout));
}

if (m_logger->is_debug_enabled()) {
Expand All @@ -134,6 +159,7 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
get_and_remove_handler(req_id);
return {};
}

return {req_id};
}

Expand All @@ -148,8 +174,11 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
* @return Channel used for the request.
*/
template<typename T>
[[nodiscard]] std::optional<std::int64_t> perform_request(protocol::client_operation op, const writer_function_type &wr,
std::function<T(protocol::reader &)> rd, ignite_callback<T> callback) {
[[nodiscard]] std::optional<std::int64_t> perform_request(
protocol::client_operation op,
const writer_function_type &wr,
std::function<T(protocol::reader &)> rd,
ignite_callback<T> callback) {
auto handler = std::make_shared<response_handler_reader<T>>(std::move(rd), std::move(callback));
return perform_request(op, wr, std::move(handler));
}
Expand Down Expand Up @@ -203,6 +232,8 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
*/
std::shared_ptr<ignite_logger> get_logger() const { return m_logger; }

void handle_timeouts();

private:
/**
* Constructor.
Expand Down Expand Up @@ -290,7 +321,7 @@ class node_connection : public std::enable_shared_from_this<node_connection> {
std::atomic_int64_t m_req_id_gen{0};

/** Pending request handlers. */
std::unordered_map<std::int64_t, std::shared_ptr<response_handler>> m_request_handlers;
std::unordered_map<std::int64_t, pending_request> m_request_handlers;

/** Handlers map mutex. */
std::recursive_mutex m_request_handlers_mutex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ class ignite_client_configuration {
*/
static constexpr std::chrono::milliseconds DEFAULT_HEARTBEAT_INTERVAL = std::chrono::seconds(30);

/**
* Default operation
*/
static constexpr std::chrono::milliseconds DEFAULT_OPERATION_TIMEOUT = std::chrono::milliseconds(0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
static constexpr std::chrono::milliseconds DEFAULT_OPERATION_TIMEOUT = std::chrono::milliseconds(0);
static constexpr std::chrono::milliseconds DEFAULT_OPERATION_TIMEOUT{0};


// Default
ignite_client_configuration() = default;

Expand Down Expand Up @@ -187,6 +192,28 @@ class ignite_client_configuration {
m_heartbeat_interval = heartbeat_interval;
}

/**
* Gets the operation timeout, in milliseconds. Default is 0 (no timeout).
*
* An "operation" is a single client request to the server. Some public API calls may involve multiple operations,
* in which case the operation timeout is applied to each individual network call.
*
* @return Operation timeout, in milliseconds.
*/
Comment on lines +195 to +202
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can see from the type it's in ms. Also, when std::chrono duration types are used it's not really important if it in milliseconds or in something else as this value can be converted freely.

Suggested change
/**
* Gets the operation timeout, in milliseconds. Default is 0 (no timeout).
*
* An "operation" is a single client request to the server. Some public API calls may involve multiple operations,
* in which case the operation timeout is applied to each individual network call.
*
* @return Operation timeout, in milliseconds.
*/
/**
* Gets the operation timeout. Default is 0 (no timeout).
*
* An "operation" is a single client request to the server. Some public API calls may involve multiple operations,
* in which case the operation timeout is applied to each individual network call.
*
* @return Operation timeout.
*/

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, let's clarify the "single request" part. I think we should clarify that the timeout is for the interval between sending a request and receiving a response to it. We can also clarify here that it's not applicable for the long running compute jobs execution, as the response is received as soon as the job is started by the cluster, and when it's done we receive a notification from the server which is a different mechanism.

[[nodiscard]] std::chrono::milliseconds get_operation_timeout() const { return m_operation_timeout; }

/**
* Sets the operation timeout.
*/
Comment on lines +205 to +207
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add some description of the parameter.

Suggested change
/**
* Sets the operation timeout.
*/
/**
* Sets the operation timeout.
*
* See @ref get_operation_timeout() for details.
*
* @param operation_timeout Operation timeout.
*/

void set_operation_timeout(std::chrono::milliseconds operation_timeout) {
if (operation_timeout.count() < 0) {
throw ignite_error(error::code::ILLEGAL_ARGUMENT, "Operation timeout can't be negative: "
Comment on lines +209 to +210
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a test for this.

+ std::to_string(operation_timeout.count()) + " microseconds");
}

m_operation_timeout = operation_timeout;
}

/**
* Gets the authenticator.
*
Expand Down Expand Up @@ -306,6 +333,9 @@ class ignite_client_configuration {
/** Heartbeat interval. */
std::chrono::milliseconds m_heartbeat_interval{DEFAULT_HEARTBEAT_INTERVAL};

/** Operation timeout. */
std::chrono::milliseconds m_operation_timeout{DEFAULT_OPERATION_TIMEOUT};

/** SSL Mode. */
ssl_mode m_ssl_mode{ssl_mode::DISABLE};

Expand Down
1 change: 1 addition & 0 deletions modules/platforms/cpp/ignite/common/error_codes.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ enum class code : underlying_t {
HANDSHAKE_HEADER = 0x30008,
SERVER_TO_CLIENT_REQUEST = 0x30009,
RESOURCE_NOT_FOUND = 0x3000a,
CLIENT_OPERATION_TIMEOUT = 0x3000b,

// Sql group. Group code: 4
QUERY_NO_RESULT_SET = 0x40001,
Expand Down
2 changes: 1 addition & 1 deletion modules/platforms/cpp/ignite/protocol/buffer_adapter.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class buffer_adapter {
*/
void reserve_length_header() {
m_length_pos = m_buffer.size();
m_buffer.insert(m_buffer.end(), 4, std::byte{0});
m_buffer.insert(m_buffer.end(), LENGTH_HEADER_SIZE, std::byte{0});
}

/**
Expand Down
12 changes: 12 additions & 0 deletions modules/platforms/cpp/tests/client-test/ignite_client_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,16 @@ TEST_F(client_test, heartbeat_disable_connection_is_closed) {
ignite_error);
}

TEST_F(client_test, connection_timeout_works) {
using namespace std::chrono_literals;

auto cfg = create_default_client_config();

cfg.set_operation_timeout(std::chrono::milliseconds{1});

auto cl = ignite_client::start(cfg, 30s);

cl.get_sql().execute(nullptr, nullptr, {"select * from dual"}, {});
}


2 changes: 1 addition & 1 deletion modules/platforms/cpp/tests/client-test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ int main(int argc, char **argv) {
runner.stop();
});

if (!check_test_node_connectable(std::chrono::seconds(5))) {
if (!check_test_node_connectable(std::chrono::seconds(5)) && false) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert.

runner.start();
ensure_node_connectable(std::chrono::seconds(60));
}
Expand Down
2 changes: 1 addition & 1 deletion modules/platforms/cpp/tests/compatibility-tests/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void set_process_abort_handler(std::function<void(int)> handler) {

using namespace ignite;

const std::vector<std::string> DEFAULT_VERSIONS = {"9.1.0", "9.1.1", "9.1.2", "9.1.3", "9.1.4"};
const std::vector<std::string> DEFAULT_VERSIONS = {"3.0.0"};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unrelated to this ticket but mistake I made in previous PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about 3.1.0?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed


/**
* Structure to store argument values for automatic memory management.
Expand Down
30 changes: 30 additions & 0 deletions modules/platforms/cpp/tests/fake_server/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

project(ignite-fake-server)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it in a separate package?


set(TARGET ${PROJECT_NAME})

set(SOURCES
main.cpp
fake_server.cpp
tcp_client_channel.cpp
response_action.cpp
connection_test.cpp
)

ignite_test(${TARGET} SOURCES ${SOURCES} LIBS ignite-test-common ignite3-client)
60 changes: 60 additions & 0 deletions modules/platforms/cpp/tests/fake_server/connection_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//
// Created by Ed on 21.11.2025.
//
Comment on lines +1 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

License


#include "tests/client-test/ignite_runner_suite.h"
#include "ignite/client/ignite_client.h"
#include "fake_server.h"

#include <gtest/gtest.h>
#include <thread>

using namespace ignite;

class connection_test : public ignite_runner_suite {

};


TEST_F(connection_test, handshake_with_fake_server) {
using namespace std::chrono_literals;
fake_server fs{};

fs.start();

ignite_client_configuration cfg;
cfg.set_logger(get_logger());
cfg.set_endpoints({"127.0.0.1:10800"});

auto cl = ignite_client::start(cfg, 5s);
}

TEST_F(connection_test, request_timeout) {
using namespace std::chrono_literals;
fake_server fs{
10800,
[](protocol::client_operation op) -> std::unique_ptr<response_action> {
switch (op) {
case protocol::client_operation::CLUSTER_GET_NODES:
return std::make_unique<drop_action>();
default:
return nullptr;
}
}
};

fs.start();

ignite_client_configuration cfg;
cfg.set_logger(get_logger());
cfg.set_endpoints({"127.0.0.1:10800"});
cfg.set_operation_timeout(std::chrono::milliseconds{100});

auto cl = ignite_client::start(cfg, 5s);

try {
auto cluster_nodes = cl.get_cluster_nodes();
} catch (ignite_error& err) {
EXPECT_EQ(error::code::CLIENT_OPERATION_TIMEOUT, err.get_status_code());
}
}
5 changes: 5 additions & 0 deletions modules/platforms/cpp/tests/fake_server/fake_server.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//
// Created by Ed on 21.11.2025.
//

#include "fake_server.h"
Comment on lines +1 to +5
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty file, let's remove.

Loading
Loading