Skip to content
Connect > Client Libraries

C++ Client

The C++ client is a native client library for C++20, ami_client_common, that connects a C++ program to 3forge Enterprise to run SQL, bulk-load tables, subscribe to live updates with server-side filters, and publish objects.

Overview

The library's whole public interface is one header, ami_client.hpp, in the namespace ami, with one entry point, ami::Client. The Python client is built on this library, so the model in Concepts applies to both. 3forge provides the library's source as a download assigned to your account, and a program builds it with CMake.

Building the library

The library needs a C++20 compiler, CMake 3.21 or later, and OpenSSL development files. It has been built with OpenSSL 3 on Linux and OpenSSL 4.1 on Windows.

On Ubuntu, install the tools with sudo apt install build-essential cmake libssl-dev.

  1. From the library's source directory, configure a release build with the tests turned off:

    cmake --preset linux-release -DAMI_BUILD_TESTS=OFF -DAMI_BUILD_FTESTS=OFF
    
  2. Build it:

    cmake --build --preset linux-release
    
  3. Check that build/linux-release/src/libami_client_common.so exists.

Install Visual Studio 2026 Build Tools with the "Desktop development with C++" workload, and the OpenSSL developer package for Windows (headers and import libraries) in C:\Program Files\OpenSSL-Win64.

  1. Open a 64-bit prompt: the "x64 Native Tools Command Prompt" for Visual Studio 2026. From the library's source directory, configure the build. CMake does not find OpenSSL on Windows by itself, so name its directory:

    cmake --preset windows-msvc -DAMI_BUILD_FTESTS=OFF "-DOPENSSL_ROOT_DIR=C:/Program Files/OpenSSL-Win64"
    
  2. Build it:

    cmake --build build/windows-msvc-x64 --config Release
    
  3. Check that build\windows-msvc-x64\src\Release holds ami_client_common.dll and ami_client_common.lib.

The source also has presets for Clang, macOS, Ninja, and MinGW, which have not been run.

To compile a program against the library, include the header's directory and link the library. AMI_SRC is the library's source directory:

g++ -std=c++20 my_program.cpp -I "$AMI_SRC" -L "$AMI_SRC/build/linux-release/src" \
    -lami_client_common -lssl -lcrypto -lpthread -o my_program

Confirm that the program links: run it with the library on the loader's path, e.g: LD_LIBRARY_PATH="$AMI_SRC/build/linux-release/src" ./my_program, and it starts without a cannot open shared object file error.

Compile from a 64-bit prompt: the "x64 Native Tools Command Prompt" for Visual Studio 2026, or a "Developer Command Prompt for VS 2026" set up with VsDevCmd.bat -arch=x64. The default prompt builds 32-bit programs, which fail to link against the 64-bit library with LNK4272 and LNK1120:

cl /std:c++20 /EHsc /O2 /I "%AMI_SRC%" my_program.cpp /link "%AMI_SRC%\build\windows-msvc-x64\src\Release\ami_client_common.lib"

Confirm that the program runs: copy ami_client_common.dll beside my_program.exe, add C:\Program Files\OpenSSL-Win64\bin to PATH, and run my_program.exe.

Connecting

A program creates one ami::Client, adds a listener, and adds an ami::Cluster with a configuration for each connection it uses.

  1. Configure the connections and add the cluster:

    ami::SslOptions keys;
    keys.trusted_server_pub_file = "3forge.pub";
    keys.client_cert_file = "client.crt.pem";
    keys.client_key_file = "client.key.pem";
    
    ami::Client client;
    client.listener_add(std::make_shared<Listener>());
    
    ami::Cluster cluster("N1", "localhost");
    cluster.database_config() = ami::DatabaseConfig("3280", true, {}, "demo", "demo123");
    cluster.database_config().shards[0].ssl = keys;
    cluster.subscription_config() = ami::SubscriptionConfig("3270");
    cluster.subscription_config().shards[0].ssl = keys;
    cluster.publication_config() = ami::PublicationConfig("3289", true, {}, "my_app");
    cluster.publication_config().shards[0].ssl = keys;
    client.add_cluster(cluster, true);
    
  2. Check that client.sql("N1", "SELECT 1")->has_result_set() is true.

Add the listener before the cluster, so it receives the first events.

A listener derives from ami::ClientListener and overrides the callbacks it needs; each has an empty default. name is the cluster name and the connection, e.g: N1-center, N1-jdbc, or N1-relay:

class Listener : public ami::ClientListener
{
public:
    void on_connect(ami::Client & client, std::string_view name) override;
    void on_disconnect(ami::Client & client, std::string_view name) override;
    void on_logged_in(ami::Client & client, std::string_view name) override;
    void on_message_sent(ami::Client & client, std::string_view name, std::string_view message) override;
    void on_message_received(ami::Client & client, std::string_view name, std::int64_t now,
                             std::int64_t seqnum, int status, std::string_view message) override;
    void on_command(ami::Client & client, std::string_view name, std::string_view request_id,
                    std::string_view cmd, std::string_view user_name, std::string_view object_type,
                    std::string_view object_id, const std::map<std::string, std::string> & params) override;
    void on_subscribe(ami::Client & client, std::string_view name, const std::vector<std::string> & tables) override;
    void on_update(ami::Client & client, std::string_view name,
                   const ami::ClientListener::CenterIncrementalUpdate & update) override;
    void on_log(ami::Client & client, std::string_view name, std::uint8_t level, std::string_view message) override;
};

on_message_received also receives the SQL connection's raw protocol frames, as unreadable text with status 0 under the -jdbc name. A listener that prints Relay replies checks for the -relay name.

Configuration Constructor
DatabaseConfig (port, use_ssl = true, failover_endpoints = {}, username, password, query_timeout_ms = 30000, query_limit = 10000, db = "")
SubscriptionConfig (port, use_ssl = true, failover_endpoints = {}, username = "", password = "")
PublicationConfig (port, use_ssl = true, failover_endpoints = {}, login_id = "", options = 0)

Each also has a form taking a host first, to override the cluster's host for that connection.

add_cluster(cluster, sync, timeout_ms) with a timeout_ms above 0 throws std::runtime_error("add_cluster timed out") if the connections are not made in time. Without it, a synchronous add_cluster returns once its wait ends, connected or not.

Check the first query, not the connection

A client whose certificate the server refuses gets no error from add_cluster, and its queries return no result set with an empty error_message(). The other signs depend on the build:

  • Linux: add_cluster returns, on_connect fires, and on_log reports an error, Synchronous operation failed: sslv3 alert bad certificate (SSL routines).
  • Windows: on_connect does not fire. on_log warns Connect to <host>:<port> failed: tls alert certificate unknown (SSL routines); next attempt in <n>s while the client retries, and a synchronous add_cluster returns only when its wait ends, with an error Synchronous operation did not complete within <n>ms ....

Running SQL

sql(cluster, statement) returns a std::unique_ptr<ami::TableAccessor>.

auto result = client.sql("N1", "SELECT sym, px FROM Quotes");
if (!result->error_message().empty()) {
    std::cerr << result->error_message() << std::endl;
}
else {
    const auto & sym = std::get<std::vector<std::string>>(result->columns()[0]);
    const auto & px = std::get<std::vector<double>>(result->columns()[1]);
    while (result->cursor_advance()) {
        auto row = result->cursor_position();
        std::cout << sym[row] << " " << px[row] << std::endl;
    }
}

Check that error_message() is empty before reading the columns: a failed statement returns no result set and the server's message, e.g: [shard 0] 009-EXCEPTION: Unknown table: Quotes.

The result object has these members:

  • has_result_set(): true for a query.
  • affected_rows(): the rows an insert, update, or delete changed.
  • columns(): one variant per column, read with std::get for its type. See Column types.
  • print(std::cout): writes the result as a text table.

sql_async(cluster, statement, callback) runs the statement in the background and calls callback(const TableAccessor &) on the callback thread.

A cluster name the client does not have returns no result set and an empty error_message(), and logs Failed to execute SQL query: Cluster not found [<name>].

Several statements separated by ; run in one call. If a later one fails, the earlier ones stay committed, and the result holds only the error, with affected_rows() of 0.

Writing tables

Build a ami::Table column by column, then upload it with sql_insert or sql_replace.

1
2
3
4
ami::Table table("Prices");
std::move(ami::Table::ColumnBuilder<std::string>("sym").emplace_value("IBM").emplace_value("AAPL")).build_into(table);
std::move(ami::Table::ColumnBuilder<double>("px", true).emplace_value(183.5).emplace_null_value()).build_into(table);
auto result = client.sql_insert("N1", std::move(table));

Check that result->affected_rows() is 2 and result->error_message() is empty.

The builder follows 3 rules:

  • A builder chain needs std::move(...): build_into takes the builder as an rvalue, so ColumnBuilder<T>(...).emplace_value(...).build_into(table) does not compile without it.
  • The template type sets the column type: see Column types. Boolean, Uuid, BigDecimal, and BigInteger columns, whose C++ values do not identify them, use add_column_as instead.
  • emplace_null_value() adds a NULL: it does so whether or not the builder was constructed with allow_null set to true. Reading back, is_null(column, row), with the column's 0-based position, is the only way to tell a NULL from a stored 0 or ""; print shows a NULL as 0.
Call Missing table Existing table
sql_insert(cluster, std::move(table)) Fails: [shard 0] 009-EXCEPTION: Table not found for Upload: <table> Appends the rows
sql_replace(cluster, std::move(table), suffix = {}) Creates it, with suffix as its table options, without the word USE Deletes every row, keeping the table and its indexes, then inserts

The async forms, sql_insert_async and sql_replace_async, take an optional callback.

sql_replace cannot create a historical table: with the suffix PersistEngine="HISTORICAL" it fails with Table not found for Upload. Create the table with sql() first, then use sql_insert.

When the server rejects the table sql_replace would create, for any reason, the error is Table not found for Upload: <table>. The server's own message, e.g: HISTORICAL does not support USE option: InitialCapacity, reaches only on_message_received, as a frame on the -jdbc connection.

Subscribing to live updates

subscribe(cluster, tables, sync) delivers each table's current rows, then every change, to on_update. unsubscribe(cluster, tables, sync) stops them.

A C++ subscription can filter rows and choose columns on the server, with ami::CenterSubscription:

1
2
3
4
5
ami::CenterSubscription quotes;
quotes.table = "Quotes";
quotes.filters = {"px > 100"};
quotes.columns = {"sym", "px"};
client.subscribe("N1", std::vector<ami::CenterSubscription>{quotes}, true);

Check that on_update receives the rows with px above 100, each with only sym and px.

A filtered subscription works as follows:

  • Only listed columns are sent: an update to a column outside the list sends nothing.
  • The filter applies when a row is first sent: a row that was sent keeps sending its updates after it stops matching, e.g: a change of px to 90 arrives. A row that matches only after a later change is never sent.
  • The update object exists only for the call: a program copies the values it keeps.
  • The action is a byte: action_ is a std::uint8_t, so it prints as a number only when cast, with static_cast<int>(update.action_), or when the whole update is printed with std::cout << update.

get_table_schema(cluster, table) returns the columns of a table this client has subscribed to, once the server has sent them. For any other table, including one that exists on the Center, it returns nothing.

Publishing objects and registering commands

publish_object(cluster, type, id, field_names, values) sends one object to the Relay:

client.publish_object("N1", "Orders", "ord-1", {"sym", "qty"}, {std::string("IBM"), std::int64_t{100}});

The Relay's replies arrive in on_message_received with status 0, e.g: OK, object accepted. Against a Relay running on Windows, they arrive instead as an on_log warning unless the PublicationConfig options include ami::PublicationConfig::UNIX_MODE; see Checking what happened to a published object. That reply does not mean a row was stored; see Publishing and the acknowledgement. A publish to a cluster name the client does not have is dropped without any message.

To add an action the platform can call, fill an ami::CommandDefinition and register it:

1
2
3
4
5
ami::CommandDefinition restart;
restart.command_id_ = "restart_feed";
restart.name_ = "Restart feed";
restart.help_ = "Restarts the market data feed";
client.register_command("N1", restart);

Check that the reply OK, command accepted arrives, in on_message_received or, against a Relay on Windows without UNIX_MODE, as an on_log warning.

Answer it in the listener's on_command, with send_command_response(cluster, request_id, status, message = {}, ami_script = {}, seqnum = 0). A command is removed when the client disconnects.

A user runs the command from the right-click menu of a real-time table panel in the Web. on_command receives the same arguments as in Python, and a command takes one row unless select_mode_ is set, e.g: std::make_pair(1, 10); see What a command call receives.

The params values are the text the Relay sends, with its type suffixes. The row's internal id arrives as o with a trailing L, e.g: 38000269L. For a command that takes several rows, V arrives in quotes, with its inner quotes escaped and a trailing J, e.g: "[{\"O\":\"o2\",\"o\":38000270}]"J. A program that needs the number or the JSON removes them first.

Disconnecting

remove_cluster(cluster, sync) closes the cluster's connections; destroying the ami::Client closes them all. on_disconnect fires for the Center connection only.

What this does not support

  • Installing a prebuilt library: the C++ client is distributed as source and built with CMake.
  • Creating a table on insert: sql_insert needs the table to exist.
  • Grouping statements in a transaction: every statement commits on its own.