Skip to content
absmartlyPublic

About

ABsmartly C++ SDK

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

57 Commits

Folders and files

Repository files navigation

A/B Smartly SDK

A/B Smartly - C++ SDK

Compatibility

The A/B Smartly C++ SDK is compatible with C++17 and later. It requires a compiler with C++17 support (GCC 7+, Clang 5+, MSVC 2017+). The SDK uses nlohmann/json for JSON handling, which is automatically fetched via CMake's FetchContent.

Installation

CMake (FetchContent)

Add the following to your CMakeLists.txt to include the SDK directly from the repository:

include(FetchContent)

FetchContent_Declare(
  absmartly-sdk
  GIT_REPOSITORY https://github.com/absmartly/cpp-sdk.git
  GIT_TAG main
)
FetchContent_MakeAvailable(absmartly-sdk)

target_link_libraries(your_target PRIVATE absmartly-sdk)

For production builds, replace main with a reviewed, fixed commit SHA (or a published release tag) so updates cannot change your build unexpectedly. SDK tests default to off when included as a dependency; a standalone build enables them by default.

CMake (Local)

If you have cloned the repository locally, you can add it as a subdirectory:

add_subdirectory(path/to/cpp-sdk)
target_link_libraries(your_target PRIVATE absmartly-sdk)

Building from Source

mkdir build && cd build
cmake ..
cmake --build .

To build without tests:

cmake -DABSMARTLY_BUILD_TESTS=OFF ..
cmake --build .

Installed Package / Release Archives

Each GitHub release (v* tag) attaches absmartly-cpp-sdk-<version>-Linux.tar.gz and .zip archives built by CPack. They contain the static library, the SDK headers (plus the bundled nlohmann/json headers) and a CMake package config. You can also install from source with cmake --install build --prefix <prefix>.

Consume an installed copy with find_package (libcurl must be available on the system):

find_package(absmartly-sdk 1.0 REQUIRED)
target_link_libraries(your_target PRIVATE absmartly::absmartly-sdk)

Getting Started

Please follow the installation instructions before trying the following code.

Initialization

This example assumes an Api Key, an Application, and an Environment have been created in the A/B Smartly web console.

Recommended: Simple Initialization

#include <absmartly/sdk.h>

int main() {
    absmartly::ClientConfig client_config;
    client_config.endpoint = "https://your-company.absmartly.io/v1";
    client_config.api_key = "YOUR_API_KEY";
    client_config.application = "website";
    client_config.environment = "production";
    auto sdk = absmartly::SDK::create_simple(client_config);

    absmartly::ContextConfig ctx_config;
    ctx_config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

    auto context = sdk->create_context(ctx_config);
    context->wait_until_ready();

    return 0;
}

Alternative: Using Configuration Objects

For use cases with custom HTTP clients or providers:

#include <absmartly/sdk.h>
#include <absmartly/client.h>
#include <absmartly/client_config.h>
#include <absmartly/sdk_config.h>
#include <absmartly/default_http_client.h>

int main() {
    absmartly::ClientConfig client_config;
    client_config.endpoint = "https://your-company.absmartly.io/v1";
    client_config.api_key = "YOUR_API_KEY";
    client_config.application = "website";
    client_config.environment = "production";

    auto http_client = std::make_shared<absmartly::DefaultHTTPClient>();
    auto client = std::make_shared<absmartly::Client>(client_config, http_client);

    absmartly::SDKConfig sdk_config;
    sdk_config.client = client;

    auto sdk = absmartly::SDK::create(sdk_config);

    absmartly::ContextConfig ctx_config;
    ctx_config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

    // Async context creation (fetches data from API)
    auto context = sdk->create_context(ctx_config);
    context->wait_until_ready();

    // Or with pre-fetched data
    auto data_future = sdk->get_context_data();
    auto data = data_future.get();
    auto context2 = sdk->create_context_with(ctx_config, data);

    return 0;
}

Direct Construction (without SDK wrapper)

#include <absmartly/context.h>
#include <absmartly/context_config.h>
#include <absmartly/models.h>
#include <nlohmann/json.hpp>

int main() {
    std::string json_response = fetch_context_data(); // your HTTP client

    absmartly::ContextData data = nlohmann::json::parse(json_response)
        .get<absmartly::ContextData>();

    absmartly::ContextConfig config;
    config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

    absmartly::Context context(config, data);

    return 0;
}

With Optional Parameters

absmartly::ContextConfig config;
config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};
config.publish_delay = 100;     // delay before publishing in milliseconds
config.refresh_period = 0;      // auto-refresh period (0 = disabled)
config.overrides = {            // pre-set treatment overrides
    {"exp_test_experiment", 1}
};
config.custom_assignments = {   // pre-set custom assignments
    {"exp_another_experiment", 0}
};

absmartly::Context context(config, data);

With Event Handler

To handle SDK events, provide a custom event handler:

#include <absmartly/context_event_logger.h>

class MyEventHandler : public absmartly::ContextEventLogger {
public:
    void handle_event(absmartly::Context& context,
                      const std::string& event_type,
                      const nlohmann::json& data) override {
        if (event_type == "exposure") {
            std::cout << "Exposed to: " << data["name"] << std::endl;
        } else if (event_type == "goal") {
            std::cout << "Goal tracked: " << data["name"] << std::endl;
        }
    }
};

// Pass the event handler as a shared_ptr
auto event_handler = std::make_shared<MyEventHandler>();
absmartly::Context context(config, data, event_handler);

SDK Options (ContextConfig)

Config Type Required? Default Description
units std::map<std::string, nlohmann::json> ✅ {} A map of unit types to unit identifiers, strings or numbers (e.g., {{"session_id", "abc123"}}).
publish_delay int ❌ -1 Delay in milliseconds before publishing events. Use -1 to publish immediately.
refresh_period int ❌ 0 Period in milliseconds for automatic context refresh. Use 0 to disable.
overrides std::map<std::string, int> ❌ {} Pre-set treatment overrides for experiments.
custom_assignments std::map<std::string, int> ❌ {} Pre-set custom assignments for experiments.

Creating a New Context

Asynchronously (Recommended)

absmartly::ClientConfig client_config;
client_config.endpoint = "https://your-company.absmartly.io/v1";
client_config.api_key = "YOUR_API_KEY";
client_config.application = "website";
client_config.environment = "production";
auto sdk = absmartly::SDK::create_simple(client_config);

absmartly::ContextConfig ctx_config;
ctx_config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

auto context = sdk->create_context(ctx_config);
context->wait_until_ready();

Direct Construction

You provide the context data obtained from your HTTP call to the A/B Smartly collector:

absmartly::ContextConfig config;
config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

absmartly::ContextData data = nlohmann::json::parse(json_response)
    .get<absmartly::ContextData>();

absmartly::Context context(config, data);
assert(context.is_ready());

With Pre-fetched Data

Creating a context involves obtaining data from the A/B Smartly event collector. You can avoid repeating the round-trip by re-using previously retrieved data:

absmartly::ContextConfig config;
config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};

absmartly::Context context(config, data);

absmartly::ContextConfig another_config;
another_config.units = {{"session_id", "another-session-id"}};

absmartly::Context another_context(another_config, context.data());
assert(another_context.is_ready());

Refreshing the Context with Fresh Experiment Data

For long-running contexts, experiments started after the context was created will not be triggered. Call the refresh() method with updated data to incorporate new experiments:

// Fetch fresh context data from the collector
absmartly::ContextData fresh_data = nlohmann::json::parse(fresh_json_response)
    .get<absmartly::ContextData>();

context.refresh(fresh_data);

Assignments are sticky across a refresh. A cached assignment is kept while the experiment's id, unit type, iteration, full-on variant and traffic split are unchanged; its audience is re-evaluated only after attributes change. An override is kept while its variant is unchanged. Calling refresh() on a context whose data failed to load does nothing (the context stays failed).

Setting Extra Units

You can add additional units to a context by calling the set_unit() or set_units() methods. This is useful when a user logs in, and you want to associate the new identity with the context. Note that you cannot override an already set unit type, as that would be a change of identity and will throw an exception. In this case, you must create a new context instead.

context.set_unit("db_user_id", "1000013");

context.set_units({
    {"db_user_id", "1000013"}
});

Basic Usage

Selecting a Treatment

if (context.treatment("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Treatment Variables

nlohmann::json variable = context.variable_value("my_variable", nlohmann::json("default"));

Variables can be of any JSON type:

nlohmann::json button_color = context.variable_value("button_color", "blue");
nlohmann::json show_banner = context.variable_value("show_banner", false);
nlohmann::json banner_height = context.variable_value("banner_height", 200);

Peek at Treatment Variants

Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The A/B Smartly SDK provides peek() and peek_variable_value() methods for that.

if (context.peek("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Peeking at Variables

nlohmann::json variable = context.peek_variable_value("my_variable", nlohmann::json("default"));

Overriding Treatment Variants

During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the set_override() and/or set_overrides() methods.

context.set_override("exp_test_experiment", 1);

context.set_overrides({
    {"exp_test_experiment", 1},
    {"exp_another_experiment", 0}
});

Advanced

Context Attributes

context.set_attribute("user_agent", "Mozilla/5.0...");

context.set_attributes({
    {"customer_age", "new_customer"},
    {"url", "/products/123"}
});

System Attributes (application / environment)

Audiences and assignment-rule conditions are always evaluated with the application and environment names from your client configuration. The SDK injects them into the attribute map it evaluates audiences against, so a filter such as {"filter":[{"eq":[{"var":"environment"},{"value":"production"}]}]} matches without you setting anything. This is always on; the collector already attaches both server-side, so nothing extra is added to the publish payload.

System values go in first and your own attributes overlay them, so a value you set under the same name always wins, even one set after the context was created (it re-evaluates cached assignments). An empty application or environment name is omitted rather than set to null/"": the key is simply absent from the evaluation map, so the result is whatever the filter yields for a missing value (an eq equality filter, for example, does not match). app_version is not injected.

When you create a context through SDK::create_context() / create_context_with(), these names are always taken from the ClientConfig, the same names the collector receives, for audiences and for assignment rules (including which environment an environment-scoped rule matches); any application or environment on the ContextConfig you pass is ignored. Only when you construct a Context directly do you set them on the ContextConfig, and they should match the names your client sends:

absmartly::ContextConfig config;
config.units = {{"session_id", "5ebf06d8cb5d8137290c4abb64155584fbdb64d8"}};
config.application = "website";
config.environment = "production";

absmartly::Context context(config, data);

Assignment Rules

Experiments can define assignment rules in the Web Console. They are evaluated in order, and the first matching rule decides the variant, taking precedence over audience targeting (including audienceStrict), traffic allocation, full-on and custom assignments. set_override() still wins over every rule.

  • An assign rule gives a fixed variant.
  • A split rule randomises the unit over its own percentages, e.g. 20/30/50, hashed with the experiment's seed. While the experiment's unit is missing, a split rule gives the full-on variant (0 for an experiment that is not full-on); once the unit is set the variant is re-randomised, unless it was already exposed.

A rule matches when its conditions evaluate to true against the context attributes (including the application/environment system attributes above) and, if it is scoped to environments, the context's environment is one of them. A rule without conditions always matches, and an empty environments list means every environment. Environment names are case-sensitive; a context without an environment never matches an environment-scoped rule.

If the first matching rule's variant is out of range, or its split does not have one percentage per variant, it is ignored and normal assignment applies; later rules are not tried. Rules that are malformed in any other way are skipped. Rule-assigned exposures are flagged ruleOverride so the backend can exclude them from analysis.

Semantic Version Operators

Audience filters and rule conditions can compare versions with semver_eq, semver_gt, semver_gte, semver_lt and semver_lte, for example against a version attribute you set:

context.set_attribute("app_version", "2.4.1");
// {"semver_gte": [{"var": "app_version"}, {"value": "2.4.0"}]} matches

A leading v or V and build metadata are ignored, missing parts count as 0, numeric parts compare numerically, and a pre-release is lower than its release (1.0.0-beta < 1.0.0). Non-version operands give no match.

SDK Identification

The SDK sends X-Agent: absmartly-cpp-sdk/<version> with every request, so the backend can report which SDK versions your applications use. The version is the CMake project version, also available as absmartly::SDK_VERSION from <absmartly/sdk_version.h>.

Custom Assignments

context.set_custom_assignment("exp_test_experiment", 1);

context.set_custom_assignments({
    {"exp_test_experiment", 1},
    {"exp_another_experiment", 0}
});

Custom Field Values

nlohmann::json field_value = context.custom_field_value("exp_test_experiment", "my_field");
std::vector<std::string> field_keys = context.custom_field_keys();

Variable Keys

auto keys = context.variable_keys();
// Returns std::map<std::string, std::vector<std::string>>
// mapping variable names to the experiments that define them

Tracking Goals

Goals are created in the A/B Smartly web console.

context.track("payment", {
    {"item_count", 1},
    {"total_amount", 1999.99}
});

Track a goal without properties:

context.track("page_view");

Publishing Pending Data

Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. You can explicitly call the publish() method, which returns a PublishEvent containing all pending data.

absmartly::PublishEvent event = context.publish();
// Serialize and send event to the A/B Smartly collector
nlohmann::json event_json = event;
send_to_collector(event_json.dump());

If the context has a ContextPublisher and it fails (throws, or returns a failed future), publish() emits an error event and rethrows. The events stay pending, so a later publish() or finalize() retries them. A failed finalize() leaves the context open.

Finalizing

The finalize() method will ensure all events have been published, like publish(), and will also "seal" the context. After that, treatment(), peek(), variable_value(), peek_variable_value(), variable_keys(), the custom field getters, publish(), refresh(), track() and the unit/attribute setters throw a ContextFinalizedException. Overrides and custom assignments remain allowed after finalization; experiments() also remains available once ready.

absmartly::PublishEvent event = context.finalize();
// Send final event to collector

Using RAII for Context Lifetime

In C++, you can use RAII patterns to ensure the context is properly finalized:

{
    absmartly::Context context(config, data);

    int treatment = context.treatment("exp_test_experiment");
    // ... use treatment

    context.track("conversion");

    // Publish and send to collector before scope ends
    auto event = context.finalize();
    send_to_collector(nlohmann::json(event).dump());
} // context destroyed here

Custom Event Handler

The A/B Smartly SDK can be instantiated with an event handler. Implement the ContextEventLogger interface to receive SDK lifecycle events.

class CustomEventHandler : public absmartly::ContextEventLogger {
public:
    void handle_event(absmartly::Context& context,
                      const std::string& event_type,
                      const nlohmann::json& data) override {
        if (event_type == "exposure") {
            std::cout << "Exposed to experiment: " << data["name"] << std::endl;
        } else if (event_type == "goal") {
            std::cout << "Goal tracked: " << data["name"] << std::endl;
        } else if (event_type == "error") {
            std::cerr << "Error: " << data.dump() << std::endl;
        }
    }
};

Usage:

auto handler = std::make_shared<CustomEventHandler>();
absmartly::Context context(config, data, handler);

Event Types

Event When Data
error Context receives an error JSON object with error details
ready Context is constructed and ready JSON with experiment list
refresh Context::refresh() method succeeds JSON with updated experiment list
publish Context::publish() method succeeds PublishEvent serialized as JSON
exposure Context::treatment() succeeds on first exposure Exposure serialized as JSON
goal Context::track() method succeeds GoalAchievement serialized as JSON
finalize Context::finalize() method succeeds the first time empty JSON

Exception Types

The SDK defines the following exception types:

Exception When
ContextFinalizedException A method is called on a finalized context ("ABsmartly Context is finalized.")
ContextFinalizingException A method is called while finalize() is publishing ("ABsmartly Context is finalizing."); derives from ContextFinalizedException
ContextNotReadyException A read (treatment(), peek(), variable_value(), peek_variable_value(), variable_keys(), experiments(), custom field getters) or publish()/refresh() is called while the context data is still loading ("ABsmartly Context is not yet ready.")

Breaking change: reads before the context is ready, and after finalize(), now throw (as the JavaScript SDK does) instead of returning 0 or the default value. Call wait_until_ready() (or check is_ready()) first. A context whose data failed to load is not "not ready": its reads return the defaults.

A Context is not thread-safe. Use each instance from one thread at a time, or guard it with your own lock.

An exception thrown by a ContextEventLogger is ignored by the SDK; it does not fail the operation that emitted the event.

About A/B Smartly

A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.

Have a look at our growing list of clients and SDKs:

About

ABsmartly C++ SDK

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages