> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust SDK

> Integrate the Kameleoon Rust SDK to run experiments and activate feature flags in Rust services and web back-ends.

With the Kameleoon Rust SDK, you can run experiments and activate feature flags in your Rust services and web back-ends.

**Getting started**: For help getting started, see the [developer guide](#developer-guide).

**Changelog**: Latest version of the Rust SDK: 0.9.5 [Changelog](https://github.com/Kameleoon/client-rust/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the Rust SDK, see the [reference](#reference) section.

## Developer guide

This guide is designed to help you integrate the Rust SDK quickly and start evaluating feature flags in your Rust application.

### Getting started

#### Install the Rust client

If you are working in the current workspace, add the SDK as a path dependency together with `tokio`, because several SDK methods are asynchronous:

```toml title="Cargo.toml" theme={null}
[dependencies]
kameleoon-client = "0.9.4"
```

#### Additional configuration

Create a `client-config.json` configuration file to provide credentials and customize SDK behavior. You can also [download our sample configuration](/assets/developer-docs/sdks/web-sdks/client-configs/client-config.json) file.

We recommend saving this file to the default path, `/etc/kameleoon/client-config.json`, but you can save it anywhere in the classpath as `client-config.json`.

The Rust SDK can be configured either with a JSON file used by `create_with_path()` or by building a `KameleoonClientConfig` with `create_with_config()` instance directly in code.

The following table shows the available properties that you can set:

| Key (Code / Config File)                                                                       | Description                                                                                                                                                                                            | Default value        |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- |
| `client_id` / `clientId` <Badge color="red" size="sm">required</Badge>                         | Required for authentication to the Kameleoon service. To find your `client_id`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.     |                      |
| `client_secret` / `clientSecret` <Badge color="red" size="sm">required</Badge>                 | Required for authentication to the Kameleoon service. To find your `client_secret`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation. |                      |
| `session_duration` / `sessionDurationMinutes` <Badge color="green" size="sm">optional</Badge>  | Time interval, in minutes, during which the SDK keeps a visitor and their associated data in memory.                                                                                                   | `30` minutes         |
| `refresh_interval` / `refreshIntervalMinutes` <Badge color="green" size="sm">optional</Badge>  | Interval, in minutes, used to refresh the active experiments and feature flags configuration.                                                                                                          | `60` minutes         |
| `default_timeout` / `defaultTimeoutMillis` <Badge color="green" size="sm">optional</Badge>     | Default timeout, in milliseconds, for SDK network requests.                                                                                                                                            | `10000` milliseconds |
| `tracking_interval` / `trackingIntervalMillis` <Badge color="green" size="sm">optional</Badge> | Interval, in milliseconds, used to batch tracking requests. Values are clamped to the `[1000, 5000]` range.                                                                                            | `1000` milliseconds  |
| `environment` / `environment` <Badge color="green" size="sm">optional</Badge>                  | Environment from which the feature flag configuration should be used. The value can be `production`, `staging`, or `development`.                                                                      | `production`         |
| `top_level_domain` / `topLevelDomain` <Badge color="green" size="sm">optional</Badge>          | The current top-level domain for your website. Use the format `example.com` without protocol or subdomains.                                                                                            | `None`               |
| `proxy_host` / `proxyHost` <Badge color="green" size="sm">optional</Badge>                     | Proxy host for outgoing SDK calls. Supported formats: `https://my.prox`, `https://my.prox:4545`, `socks5://192.168.1.1:9000`.                                                                          | `None`               |
| `network_domain` / `networkDomain` <Badge color="green" size="sm">optional</Badge>             | Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon's value.                     | `None`               |

#### Initialize the Kameleoon client

After you have installed the SDK and configured your credentials, create a `KameleoonClient` by using `KameleoonClientFactory`.

<Tabs>
  <Tab title="Config File">
    ```rust theme={null}
    use std::time::Duration;

    use kameleoon_client::config::KameleoonClientConfigBuilder;
    use kameleoon_client::factory::KameleoonClientFactory;

    async fn create_client() -> Result<KameleoonClient, KameleoonError> {
        let site_code = "a8st4f59bj";

        let client = KameleoonClientFactory::create_with_path(site_code, "/etc/kameleoon/client-config.json")?;
        client.initialize().await?;

        Ok(client)
    }
    ```
  </Tab>

  <Tab title="Code">
    ```rust theme={null}
    use std::time::Duration;

    use kameleoon_client::config::KameleoonClientConfigBuilder;
    use kameleoon_client::factory::KameleoonClientFactory;

    async fn create_client() -> Result<KameleoonClient, KameleoonError> {
        let site_code = "a8st4f59bj";

        let config = KameleoonClientConfigBuilder::default()
            .client_id("<client-id>".to_owned())                // mandatory
            .client_secret("<client-secret>".to_owned())        // mandatory
            .refresh_interval(Duration::from_mins(60))          // optional (60 minutes by default)
            .session_duration(Duration::from_mins(30))          // optional (30 minutes by default)
            .default_timeout(Duration::from_millis(10_000))     // optional (10000 ms by default)
            .tracking_interval(Duration::from_millis(1_000))    // optional (1000 ms by default)
            .environment("development".to_owned())              // optional
            .top_level_domain(".example.com")                   // mandatory if you use hybrid mode (engine or web experiments)
            .proxy_host("http://192.168.0.25:8080".to_owned())  // optional
            .network_domain("example.com".to_owned())           // optional
            .build()
            .unwrap();

        let client = KameleoonClientFactory::create_with_config(site_code, config)?;
        client.initialize().await?;

        Ok(client)
    }
    ```
  </Tab>
</Tabs>

A `KameleoonClient` is the main object used to evaluate feature flags, add visitor data, and send tracking requests.

<Warning>
  * It is recommended to use `KameleoonClient` as a singleton object, as it serves as the bridge between your application and the Kameleoon platform. It exposes all required methods and properties to run experiments efficiently.
  * The Rust SDK initializes asynchronously. You should call [`initialize()`](#initialize) before relying on feature evaluation in production code.
</Warning>

#### Activating a feature flag

##### Assigning a unique ID to a user

To assign a unique ID to a user, you can use the [`get_visitor_code()`](#get_visitor_code) method. If a **visitor code** doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a `default_visitor_code` that you would have generated. The ID is then set in a response headers cookie.

If you are using Kameleoon in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation), calling the `get_visitor_code()` method ensures that the unique ID (**visitor code**) is shared between the application file `engine.js` (previously named, `kameleoon.js`) and the SDK.

##### Retrieving a flag configuration

To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.

To determine the status or variation of a feature flag for a specific user, you should use the [`get_variation()`](#get_variation) or [`is_feature_active()`](#is_feature_active) method to retrieve the configuration based on the `feature_key`.

The `get_variation()` method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the `feature_key` and `visitor_code`.

The `is_feature_active()` method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.

If your feature flag has associated variables (such as specific behaviors tied to each variation) `get_variation()` also enables you to access the [`Variation`](#variation) object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When `track=true`, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s [`tracking_interval`](#additional-configuration). By default, this interval is set to 1000 milliseconds (1 second).

The `get_variation()` method allows you to control whether tracking is done. If `track=false`, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting `track=false` is helpful when using the `get_variations()` method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view [this article](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### Adding data points to target a user or filter / breakdown visits in reports

To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the [`add_data()`](#add_data) method to add these data points to the user's profile.

To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the [`get_remote_visitor_data()`](#get_remote_visitor_data) method. This method asynchronously fetches data from the servers. It is important to call `get_remote_visitor_data()` *before* retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.

To learn more about available targeting conditions, see the [detailed article on the subject](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list [here](/user-manual/experiment-analytics/analyze-results/results-page-settings#breakdown-audience).

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's [Custom Data feature](#customdata). Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the [`flush()`](#flush) method to send the collected data to Kameleoon servers for analysis.

<Note>
  To ensure your results are accurate, it's recommended to filter out bots by using the [`UserAgent`](#useragent) data type.
</Note>

##### Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the [`track_conversion()`](#track_conversion) method and provide the required `visitor_code` and `goal_id` parameters.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by [`tracking_interval`](#additional-configuration)). If you prefer to send the request immediately, use the [`flush_instant()`](#flush) method.

##### Sending events to analytics solutions

To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/). Then, use the [`get_engine_tracking_code()`](#get_engine_tracking_code) method.

The `get_engine_tracking_code()` method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

### Using a custom bucketing key

By default, Kameleoon uses a unique, anonymous visitor ID (`visitor_code`) to assign users to feature flag variations. This ID is typically generated and stored on the user's device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.

The **Custom Bucketing Key** option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon's assignment logic uses your specified key instead of the default `visitor_code`.

#### Use cases

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:

* **Account-level or organizational experiments:** For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an `account_id`. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.

By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, leading to more reliable results and a better user experience.

#### Technical details

When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application's data:

```rust theme={null}
use kameleoon_client::data::CustomData;

client.add_data(visitor_code, [CustomData::new(42, vec!["new_visitor_code".to_owned()])])?;
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`add_data()`](#add_data) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `new_visitor_code` refers to the identifier you wish to use for your bucketing (for example, the new `user_id` or `account_id`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `add_data()` method, all hash calculations for assigning users to variations will use this `new_visitor_code` (your custom key) instead of the default `visitor_code`. Using the `new_visitor_code` means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
* **Data tracking and analytics:** It's crucial to note that while the `new_visitor_code` (your custom key) is used for bucketing decisions, **all subsequent data (tracking events and conversions, for example) is sent and associated with the *original* `visitor_code`.** This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment's broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

#### Technical requirements

To effectively use a custom bucketing key:

* The key must be a `&str`.
* It must be unique for the entity you intend to bucket (for example, if using a `user_id`, each user's ID should be unique).
* The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.

### Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see [use visit history to target users](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users).

### Cross-device experimentation

To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor's devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the [article on cross-device experimentation](/developer-docs/cross-device-experimentation).

#### Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

**Same user ID across devices**
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the `get_remote_visitor_data()` method when you want to sync the data collected between multiple devices.

**Multi-server instances with consistent IDs**
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with `get_remote_visitor_data()`) is sufficient without additional custom mapping sync.

Customers who need additional data can refer to the [`get_remote_visitor_data()`](#get_remote_visitor_data) method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the `visitor_code`, which can also be referred to as `userId`) is used consistently between the two devices for accurate data retrieval.

<Note>
  If you want to sync collected data in real time, you need to choose the scope **Visitor** for your custom data.
</Note>

```rust title="Device A" theme={null}
// In this example, a Custom data with index `90` was set to "Visitor" scope in Kameleoon.
use kameleoon_client::data::CustomData;

const VISITOR_SCOPE_CUSTOM_DATA_INDEX: u32 = 90;

client.add_data(visitor_code, [CustomData::new(VISITOR_SCOPE_CUSTOM_DATA_INDEX, vec!["your data".to_owned()])])?;

client.flush_instant(visitor_code).await?;
```

```rust title="Device B" theme={null}
// Before working with the data, call the `get_remote_visitor_data` method.
client.get_remote_visitor_data(visitor_code, None).await?;

// After calling the method, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available for targeting and tracking the visitor.
```

#### Using custom data for session merging

[Cross-device experimentation](/developer-docs/cross-device-experimentation) allows for combining a visitor's history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, use [`CustomData`](#customdata) to provide a unique identifier for the visitor. For more information, see the [dedicated documentation](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

After cross-device reconciliation is enabled, calling [`get_remote_visitor_data()`](#get_remote_visitor_data) with the parameter `userId` retrieves all known data for a given user.

Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment's results pages, these sessions will appear as a single visitor.

The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. These limitations are outlined [here](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Follow the [activating cross-device history reconciliation](#cross-device-experimentation) guide to set up your custom data on the Kameleoon platform.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

* `get_remote_visitor_data()` with added `UniqueIdentifier(true)` - to retrieve data for all linked visitors.
* [`track_conversion()`](#track_conversion) or [`flush()`](#flush) with added `UniqueIdentifier(true)` data - to track some data for specific visitor that is associated with another visitor.

<Tip>
  As the custom data you use as the identifier must be set to **Visitor scope**, you need to use [cross-device custom data synchronization](/developer-docs/cross-device-experimentation) to retrieve the identifier with the [`get_remote_visitor_data()`](#get_remote_visitor_data) method on each device.
</Tip>

Here's an example of how to use custom data for session merging.

```rust theme={null}
// In this example, 91 represents the Custom Data's index configured as a unique identifier in Kameleoon.
use kameleoon_client::data::{CustomData, UniqueIdentifier};

const MAPPING_INDEX: u32 = 91;
const FEATURE_KEY: &str = "ff123";

let anonymous_visitor_code = "anonymous-visitor";
let user_id = "authenticated-user";

// 1. Before the visitor is authenticated

// Retrieve the variation for an unauthenticated visitor.
// Assume anonymousVisitorCode is the randomly generated ID for that visitor.
let anonymous_variation = client.get_variation(anonymous_visitor_code, FEATURE_KEY)?;

// 2. After the visitor is authenticated

// Assume `userId` is the visitor code of the authenticated visitor.
client.add_data(anonymous_visitor_code, [CustomData::new(MAPPING_INDEX, vec![user_id.to_owned()])])?;
client.flush_instant(anonymous_visitor_code).await?;

// Indicate that `userId` is a unique identifier.
client.add_data(user_id, [UniqueIdentifier::new(true)])?;

// 3. After the visitor was authorized

// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
let user_variation = client.get_variation(user_id, FEATURE_KEY)?;
let is_same_variation = user_variation.key.as_ref() == anonymous_variation.key.as_ref(); // true

// `userId` and `anonymousVisitorCode` are now linked and can be tracked as a single visitor.
client.track_conversion(user_id, 123)?;

// Additionally, the linked visitors share all fetched previously tracked remote data.
client.get_remote_visitor_data(user_id, None).await?;
```

In this example, the application has a login page. Since the user ID is unknown at the moment of login, an anonymous visitor identifier generated by the [`get_visitor_code()`](#get_visitor_code) method is used. After the user logs in, the anonymous visitor is associated with the user ID and used as a unique identifier for the visitor.

### Logging

The SDK generates logs to reflect various internal processes and issues.

#### Log levels

The SDK supports configuring limiting logging by a log level.

```rust theme={null}
use kameleoon_client::logging::{KameleoonLogger, LogLevel};

// The `None` log level does not allow logging.
KameleoonLogger::set_log_level(LogLevel::None);

// The `Error` log level only allows logging issues that may affect the SDK's primary behaviour.
KameleoonLogger::set_log_level(LogLevel::Error);

// The `Warning` log level allows logging issues which may require attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is the default log level.
KameleoonLogger::set_log_level(LogLevel::Warning);

// The `Info` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger::set_log_level(LogLevel::Info);

// The `Debug` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
KameleoonLogger::set_log_level(LogLevel::Debug);
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```rust theme={null}
use kameleoon_client::logging::{KameleoonLogger, LogLevel, Logger};
use log::{error, warn, info, debug};

pub struct CustomLogger;

impl Logger for CustomLogger {
    // `log` method accepts logs from the SDK
    fn log(&self, log_level: LogLevel, message: &str) {
        // Custom log handling logic here. For example:
        match log_level {
            LogLevel::Error   => error!("{}", message),
            LogLevel::Warning => warn!("{}", message),
            LogLevel::Info    => info!("{}", message),
            LogLevel::Debug   => debug!("{}", message),
        }
    }
}
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger::set_log_level(LogLevel::Debug); // Optional; defaults to `LogLevel.WARNING`.
KameleoonLogger::set_logger(Box::new(CustomLogger));
```

## Reference

This is the full reference documentation for the Rust SDK.

### Initialization

#### create()

To use the SDK, create a `KameleoonClient` from a `KameleoonClientConfig` instance with `KameleoonClientFactory::create_with_config()`/`KameleoonClientFactory::create_with_file()`.

<Tabs>
  <Tab title="create_with_config()">
    ```rust theme={null}
    use std::time::Duration;

    use kameleoon_client::config::KameleoonClientConfigBuilder;
    use kameleoon_client::factory::KameleoonClientFactory;

    let config = KameleoonClientConfigBuilder::default()
        .client_id("<client-id>".to_owned())                // mandatory
        .client_secret("<client-secret>".to_owned())        // mandatory
        .refresh_interval(Duration::from_mins(60))          // optional (60 minutes by default)
        .session_duration(Duration::from_mins(30))          // optional (30 minutes by default)
        .default_timeout(Duration::from_millis(10_000))     // optional (10000 ms by default)
        .tracking_interval(Duration::from_millis(1_000))    // optional (1000 ms by default)
        .environment("development".to_owned())              // optional
        .top_level_domain(".example.com")                   // mandatory if you use hybrid mode (engine or web experiments)
        .proxy_host("http://192.168.0.25:8080".to_owned())  // optional
        .network_domain("example.com".to_owned())           // optional
        .build()
        .unwrap();

    let client = KameleoonClientFactory::create_with_config(site_code, config)?;
    ```

    ##### Parameters

    | Name                                                      | Type                    | Description                                          |
    | --------------------------------------------------------- | ----------------------- | ---------------------------------------------------- |
    | `site_code` <Badge color="red" size="sm">required</Badge> | `&str`                  | Unique key of the Kameleoon project used by the SDK. |
    | `config` <Badge color="red" size="sm">required</Badge>    | `KameleoonClientConfig` | SDK configuration object.                            |
  </Tab>

  <Tab title="create_with_file()">
    ```rust theme={null}
    use kameleoon_client::factory::KameleoonClientFactory;

    let client = KameleoonClientFactory::create_with_file("a8st4f59bj", "/etc/kameleoon/client-config.json")?;
    ```

    ##### Parameters

    | Name                                                        | Type   | Description                                          |
    | ----------------------------------------------------------- | ------ | ---------------------------------------------------- |
    | `site_code` <Badge color="red" size="sm">required</Badge>   | `&str` | Unique key of the Kameleoon project used by the SDK. |
    | `config_path` <Badge color="red" size="sm">required</Badge> | `&str` | Path to the JSON configuration file.                 |
  </Tab>
</Tabs>

##### Return value

| Type                                      | Description                                                      |
| ----------------------------------------- | ---------------------------------------------------------------- |
| `Result<KameleoonClient, KameleoonError>` | A client instance on success, otherwise an initialization error. |

##### Errors

| Type                                  | Description                      |
| ------------------------------------- | -------------------------------- |
| `ErrorCode::ConfigCredentialsInvalid` | The SDK credentials are missing. |
| `ErrorCode::SiteCodeIsEmpty`          | The provided site code is empty. |

#### initialize()

Waits for the Kameleoon client to initialize, using either the configured [`default_timeout`](#additional-configuration) or a provided `timeout`. This method ensures that the client is fully initialized before performing any further operations.

```rust theme={null}
use std::time::Duration;

// Initializes the client using the configured default timeout
client.initialize().await?;

// Initializes the client with a custom timeout of 5 seconds
client.initialize_with_timeout(Duration::from_secs(5)).await?;
```

##### Parameters

| Name                                                      | Type       | Description                              |
| --------------------------------------------------------- | ---------- | ---------------------------------------- |
| `timeout` <Badge color="green" size="sm">optional</Badge> | `Duration` | Maximum time to wait for initialization. |

##### Return value

| Type                         | Description                                                                   |
| ---------------------------- | ----------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether initialization completed successfully or an error occurred. |

##### Errors

| Type                        | Description                                          |
| --------------------------- | ---------------------------------------------------- |
| `ErrorCode::Initialization` | Indicates that the SDK is not yet fully initialized. |

#### is\_ready()

Checks whether the client has been initialized.

```rust theme={null}
if client.is_ready() {
    // The client is ready
}
```

##### Return value

| Type   | Description                                                  |
| ------ | ------------------------------------------------------------ |
| `bool` | `true` if the client is ready to be used; otherwise `false`. |

#### forget()

Removes the cached SDK client associated with the specified `site_code`.

```rust theme={null}
use kameleoon_client::factory::KameleoonClientFactory;

// Removes the cached client for the given site code
KameleoonClientFactory::forget("a8st4f59bj")?;

// Removes the cached client for the given site code and environment
KameleoonClientFactory::forget_with_environment("a8st4f59bj", "production")?;
```

##### Parameters

| Name                                                          | Type   | Description                                        |
| ------------------------------------------------------------- | ------ | -------------------------------------------------- |
| `site_code` <Badge color="red" size="sm">required</Badge>     | `&str` | Unique identifier of the Kameleoon project.        |
| `environment` <Badge color="green" size="sm">optional</Badge> | `&str` | Environment key associated with the cached client. |

##### Return value

| Type                         | Description                                                                        |
| ---------------------------- | ---------------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether the cached client was successfully removed or an error occurred. |

### Feature flags and variations

#### is\_feature\_active()

* 📨 *Sends tracking data to Kameleoon (depending on the `track` option)*

Determines whether a feature flag is active for a given user.

If the visitor has not yet been evaluated for this feature flag, the SDK evaluates the targeting rules and returns the result. If the visitor already has a stored evaluation for the feature, the SDK reuses the existing result to ensure consistency.

<Note>
  Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as `is_feature_active()`, `get_variation()` or `get_variations()`.

  Use the default `true` value for the `track` parameter when you expose visitors to a variation and need to count them. Set the `track` parameter to `false` only if you call these methods before you expose visitors.

  For example, if you call `get_variations()` to retrieve all variations before you expose visitors, set the `track` parameter to `false`. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.

  Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
</Note>

<Warning>
  The `is_feature_active()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

```rust theme={null}
use kameleoon_client::client::IsFeatureActiveOpts;

let feature_key = "new_checkout";

// Evaluates the feature flag and sends tracking data (default behavior)
let active = client.is_feature_active(visitor_code, feature_key)?;

// Evaluates the feature flag without sending tracking data
let active_without_tracking = client.is_feature_active_with_opts(
    visitor_code,
    feature_key,
    IsFeatureActiveOpts::new().track(false),
)?;
```

##### Parameters

| Name                                                         | Type   | Description                                             | Default |
| ------------------------------------------------------------ | ------ | ------------------------------------------------------- | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str` | Unique identifier of the user.                          |         |
| `feature_key` <Badge color="red" size="sm">required</Badge>  | `&str` | Key of the feature to evaluate for the user.            |         |
| `track` <Badge color="green" size="sm">optional</Badge>      | `bool` | Enables or disables tracking of the feature evaluation. | `true`  |

##### Return value

| Type                           | Description                                                                                         |
| ------------------------------ | --------------------------------------------------------------------------------------------------- |
| `Result<bool, KameleoonError>` | Indicates whether the feature flag is active for the specified `visitor_code`, or returns an error. |

##### Errors

| Type                            | Description                                                                                                                                                                                                                                                           |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                                                                                                                                                                  |
| `ErrorCode::FeatureNotFound`    | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |

#### get\_variation()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves the [`Variation`](#variation) assigned to a given visitor for a specific feature flag.

This method takes a `visitor_code` and `feature_key` as mandatory arguments. The `track` argument is optional and defaults to `true`.

It returns the assigned `Variation` for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default `Variation` for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```rust theme={null}
use kameleoon_client::client::GetVariationOpts;

let feature_key = "new_checkout";

// Retrieves the variation assigned to the visitor (with tracking enabled by default)
let variation = client.get_variation(visitor_code, feature_key)?;

// Retrieves the variation without sending tracking data
let variation_without_tracking = client.get_variation_with_opts(
    visitor_code,
    feature_key,
    GetVariationOpts::new().track(false),
)?;
```

##### Parameters

| Name                                                         | Type   | Description                                                                    | Default |
| ------------------------------------------------------------ | ------ | ------------------------------------------------------------------------------ | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str` | Unique identifier of the visitor.                                              |         |
| `feature_key` <Badge color="red" size="sm">required</Badge>  | `&str` | Key of the feature you want to expose to a visitor.                            |         |
| `track` <Badge color="green" size="sm">optional</Badge>      | `bool` | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type                                | Description                                                                                                          |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `Result<Variation, KameleoonError>` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag on success, otherwise an error. |

##### Errors

| Type                                    | Description                                                                                                                                                                                                                                                           |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`             | Indicates that the SDK is not yet fully initialized.                                                                                                                                                                                                                  |
| `ErrorCode::VisitorCodeInvalid`         | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |
| `ErrorCode::FeatureNotFound`            | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `ErrorCode::FeatureEnvironmentDisabled` | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                          |
| `ErrorCode::FeatureEvaluationBlocked`   | Exception indicating that feature evaluation is blocked. The reason is described in the error message. This usually occurs due to GDPR restrictions when the visitor has not provided legal consent.                                                                  |

#### get\_variations()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves a map of [`Variation`](#variation) objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned `Variation` for each flag associated with the specified visitor. It takes `visitor_code` as a mandatory argument, while `only_active` and `track` are optional.

* If `only_active` is set to `true`, the method `get_variations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding `Variation` as values. If no variation is assigned for a feature flag, the method returns the default `Variation` for that flag.

Proper error handling should be implemented to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```rust theme={null}
use kameleoon_client::client::GetVariationsOpts;

// Retrieves all variations assigned to the visitor (with default options)
let variations = client.get_variations(visitor_code)?;

// Retrieves only active variations for the visitor
let only_active_variations = client.get_variations_with_opts(
    visitor_code,
    GetVariationsOpts::new().only_active(true),
)?;

// Retrieves variations without sending tracking data
let variations_without_tracking = client.get_variations_with_opts(
    visitor_code,
    GetVariationsOpts::new().track(false),
)?;
```

##### Parameters

| Name                                                          | Type   | Description                                                                                                       | Default |
| ------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge>  | `&str` | Unique identifier of the visitor.                                                                                 |         |
| `only_active` <Badge color="green" size="sm">optional</Badge> | `bool` | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `track` <Badge color="green" size="sm">optional</Badge>       | `bool` | An optional parameter to enable or disable tracking of the feature evaluation.                                    | `true`  |

##### Return value

| Type                                                   | Description                                                                                                                                                        |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Result<HashMap<Arc<str>, Variation>, KameleoonError>` | Map that contains the assigned [`Variation`](#variation) objects of the feature flags using the keys of the corresponding features on success, otherwise an error. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### set\_forced\_variation()

The method allows you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.

When a **forced** variation is set, it overrides Kameleoon's real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `force_targeting=false` instead.

<Info>
  **Simulated** variations always take precedence in the execution order. If a **simulated** variation calculation is triggered, it will be fully processed and completed first.
</Info>

A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.

The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.

<Warning>
  It’s important to distinguish **forced** variations from **[simulated](#get_visitor_code)** variations:

  * **Forced variations**: Are specific to an individual experiment.
  * **Simulated variations**: Affect the overall **feature flag** result.
</Warning>

```rust theme={null}
use kameleoon_client::client::SetForcedVariationOpts;

let experiment_id = 202387;

// Forces the visitor into "variation_2" for the given experiment
client.set_forced_variation(visitor_code, experiment_id, Some("variation_2"))?;

// Removes any previously forced variation for the visitor in this experiment
client.set_forced_variation(visitor_code, experiment_id, None)?;

// Forces the visitor into "variation_2" with custom options
// In this case, targeting rules are respected (force_targeting = false)
client.set_forced_variation_with_opts(
    visitor_code,
    experiment_id,
    Some("variation_2"),
    SetForcedVariationOpts::new().force_targeting(false),
)?;
```

##### Parameters

| Name                                                              | Type           | Description                                                                                                                                                                  | Default |
| ----------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge>      | `&str`         | Unique identifier of the visitor.                                                                                                                                            |         |
| `experiment_id` <Badge color="red" size="sm">required</Badge>     | `u32`          | **Experiment Id** that will be targeted and selected during the evaluation process.                                                                                          |         |
| `variation_key` <Badge color="red" size="sm">required</Badge>     | `Option<&str>` | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `None`, the forced variation will be reset. |         |
| `force_targeting` <Badge color="green" size="sm">optional</Badge> | `bool`         | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`).                             | `true`  |

##### Return value

| Type                         | Description                                                                       |
| ---------------------------- | --------------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether the forced variation was successfully set or an error occurred. |

##### Errors

| Type                                   | Description                                                                                                                                                                                                                                           |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`            | Indicates that the SDK is not yet fully initialized.                                                                                                                                                                                                  |
| `ErrorCode::VisitorCodeInvalid`        | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                   |
| `ErrorCode::FeatureExperimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `ErrorCode::FeatureVariationNotFound`  | Exception indicating that the requested variation key(id) has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |

#### evaluate\_audiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`evaluate_audiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.

After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.

```rust theme={null}
client.evaluate_audiences(visitor_code)?;
```

##### Parameters

| Name                                                         | Type   | Description                       |
| ------------------------------------------------------------ | ------ | --------------------------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str` | Unique identifier of the visitor. |

##### Return value

| Type                         | Description                                                           |
| ---------------------------- | --------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether audience evaluation succeeded or an error occurred. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### get\_datafile()

<Tip>
  To evaluate all feature flags, use [`get_variations()`](#get_variations). This method is more efficient than calling `DataFile` and iterating through flags with [`get_variation()`](#get_variation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```rust theme={null}
let datafile = client.get_datafile()?;
```

##### Return value

| Type                                    | Description                                                                                  |
| --------------------------------------- | -------------------------------------------------------------------------------------------- |
| `Result<Arc<DataFile>, KameleoonError>` | The [`DataFile`](#datafile) containing the SDK configuration on success, otherwise an error. |

##### Errors

| Type                        | Description                                          |
| --------------------------- | ---------------------------------------------------- |
| `ErrorCode::Initialization` | Indicates that the SDK is not yet fully initialized. |

### Visitor data

#### get\_visitor\_code()

Use `get_visitor_code()` to obtain the current visitor's Kameleoon `visitor_code`. The method works with any cookie store that implements the `CookieAccessor` trait.

The implementation logic is as follows:

1. The SDK checks whether a `kameleoonVisitorCode` cookie is already available through the provided accessor.
2. If the cookie is absent, the SDK uses `default_visitor_code` when you provide one.
3. Otherwise, the SDK generates a new visitor code and stores it through the accessor.

For more information, refer to [Hybrid experimentation](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/).

<Warning>
  If you provide your own `visitor_code`, its uniqueness must be guaranteed on your side. Also note that the length of `visitor_code` is limited to `255` characters.
</Warning>

<Info>
  The `get_visitor_code()` method allows you to set **simulated** variations for a visitor. When cookies (from a **request** or **document**) contain the key `kameleoonSimulationFFData`, the standard evaluation process is bypassed. Instead, the method directly returns a [`Variation`](#variation) based on the provided data.

  You can apply simulations in two ways:

  * **Automatically (recommended):** If using Kameleoon Web Experimentation or the SDK in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation#linking-feature-experiments-with-front-end-tracking-code), the cookie is created automatically when simulating a variant's display using the [Simulation Panel](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/validation-and-rollback/using-simulation-mode).
  * **Manually:** Set the `kameleoonSimulationFFData` cookie manually.

  It’s important to distinguish **simulated** variations from **[forced](#set_forced_variation)** variations:

  * **Simulated variations**: Affect the overall **feature flag** result.
  * **Forced variations**: Are specific to an individual experiment.

  ⚙️ **Manual setup**

  Please ensure the `kameleoonSimulationFFData` cookie follows this format:

  * `kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}`: Simulates the variation with `varId` of experiment `expId` for the given `featureKey`.
  * `kameleoonSimulationFFData={"featureKey":{"expId":0}}`: Simulates the default variation (defined in the **Then, for everyone else in Production, serve** section) for the given `featureKey`.

  ⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
</Info>

<Tabs>
  <Tab title="Custom">
    ```rust theme={null}
    use std::collections::HashMap;

    use kameleoon_client::cookies::CookieAccessor;

    // A simple in-memory cookie store, useful for testing or non-HTTP environments
    struct MemoryCookies {
        values: HashMap<String, String>,
    }

    impl CookieAccessor for MemoryCookies {
        // Store the cookie value by key (max_age and top_level_domain are unused here)
        fn set<'a>(&mut self, key: &str, value: &str, _max_age: u32, _top_level_domain: Option<&'a str>) {
            self.values.insert(key.to_owned(), value.to_owned());
        }

        // Retrieve a cookie value by key
        fn get(&self, key: &str) -> Option<&str> {
            self.values.get(key).map(String::as_str)
        }
    }

    // Generate or retrieve a visitor code using auto-generated value
    let visitor_code = client.get_visitor_code(&mut cookies, None)?;
    // Generate or retrieve a visitor code using a predefined user ID
    let visitor_code = client.get_visitor_code(&mut cookies, Some("user_id"))?;
    ```
  </Tab>

  <Tab title="Axum">
    ```rust theme={null}
    use axum::{ extract::State, http::StatusCode, response::{IntoResponse, Response} };
    use axum_extra::extract::cookie::{Cookie, CookieJar};
    use kameleoon_client::client::KameleoonClient;
    use kameleoon_client::cookies::CookieAccessor;
    use time::Duration;

    // Wrapper around Axum's CookieJar to implement the CookieAccessor trait
    struct AxumCookies(CookieJar);

    impl CookieAccessor for AxumCookies {
        // Build and add a cookie with path, max_age, and optional domain, then insert into the jar
        fn set<'a>(&mut self, key: &str, value: &str, max_age: u32, top_level_domain: Option<&'a str>) {
            let mut builder =
                Cookie::build((key.to_owned(), value.to_owned())).path("/").max_age(Duration::seconds(i64::from(max_age)));
            if let Some(domain) = top_level_domain {
                builder = builder.domain(domain.to_owned());
            }
            self.0 = std::mem::take(&mut self.0).add(builder.build());
        }

        // Retrieve a cookie value by key from the jar
        fn get(&self, key: &str) -> Option<&str> {
            self.0.get(key).map(|cookie| cookie.value())
        }
    }

    async fn get_visitor_code(
        State(client): State<KameleoonClient>,
        jar: CookieJar,
    ) -> Result<(StatusCode, CookieJar, String), Response> {
        let mut cookies = AxumCookies(jar);

        // Retrieve or generate a visitor code; map any SDK error to a 500 response
        let visitor_code = client
            .get_visitor_code(&mut cookies, None)
            .map_err(|error| (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response())?;

        // Return the status, updated cookie jar, and visitor code in the response
        Ok((StatusCode::OK, cookies.0, visitor_code))
    }
    ```
  </Tab>

  <Tab title="Actix">
    ```rust theme={null}
    use actix_web::{ HttpRequest, HttpResponse, cookie::Cookie, http::{StatusCode, header}, web};
    use kameleoon_client::client::KameleoonClient;
    use kameleoon_client::cookies::CookieAccessor;
    use kameleoon_client::error::KameleoonError;
    use time::Duration;

    // Holds both request cookies (read-only) and response cookies (to be set on the client)
    struct ActixCookies<'a> {
        request: Ref<'a, Vec<Cookie<'static>>>,
        response: Vec<Cookie<'static>>,
    }

    impl CookieAccessor for ActixCookies<'_> {
        // Build a cookie with path, max_age, and optional domain;
        // update it if it already exists in the response, otherwise append it
        fn set<'a>(&mut self, key: &str, value: &str, max_age: u32, top_level_domain: Option<&'a str>) {
            let mut builder =
                Cookie::build(key.to_owned(), value.to_owned()).path("/").max_age(Duration::seconds(i64::from(max_age)));
            if let Some(domain) = top_level_domain {
                builder = builder.domain(domain.to_owned());
            }
            let next_cookie = builder.finish();

            match self.response.iter_mut().find(|cookie| cookie.name() == key) {
                Some(cookie) => *cookie = next_cookie,
                None => self.response.push(next_cookie),
            }
        }

        // Check response cookies first, then fall back to request cookies
        fn get(&self, key: &str) -> Option<&str> {
            self.response
                .iter()
                .find(|cookie| cookie.name() == key)
                .map(|cookie| cookie.value())
                .or_else(|| self.request.iter().find(|cookie| cookie.name() == key).map(|cookie| cookie.value()))
        }
    }

    fn get_visitor_code(client: web::Data<KameleoonClient>, request: HttpRequest) -> Result<HttpResponse, KameleoonError> {
        // Parse cookies from the incoming request
        let request_cookies = request.cookies().map_err(|error| error.to_string())?;
        let mut cookies = ActixCookies {
            request: request_cookies,
            response: Vec::new(),
        };

        // Retrieve or generate a visitor code using the SDK
        let visitor_code = client.get_visitor_code(&mut cookies, None)?;

        // Attach any new/updated cookies to the response headers
        let mut response = HttpResponse::build(StatusCode::OK);
        for cookie in cookies.response {
            response.append_header((header::SET_COOKIE, cookie.encoded().to_string()));
        }

        Ok(response.body(visitor_code))
    }
    ```
  </Tab>
</Tabs>

##### Parameters

| Name                                                                   | Type                       | Description                                                        |
| ---------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------ |
| `cookies` <Badge color="red" size="sm">required</Badge>                | `&mut impl CookieAccessor` | Mutable cookie accessor used to read and store the visitor cookie. |
| `default_visitor_code` <Badge color="green" size="sm">optional</Badge> | `Option<&str>`             | Visitor code to use when no cookie is present.                     |

##### Return value

| Type                             | Description                                                                           |
| -------------------------------- | ------------------------------------------------------------------------------------- |
| `Result<String, KameleoonError>` | String representing a unique visitor code used in SDK on success, otherwise an error. |

#### add\_data()

The `add_data()` method adds [targeting data](#data-types) to storage so other methods can use the data to decide whether or not to target the current visitor.

The `add_data()` method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the [`flush()`](#flush) method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered by the `flush()`.

The [`track_conversion()`](#track_conversion) method also sends out any previously associated data, just like the `flush()`. The same holds true for [`get_variation()`](#get_variation) and [`get_variations()`](#get_variations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```rust theme={null}
use kameleoon_client::data::{Browser, BrowserKind, PageView, UserAgent};

client.add_data(visitor_code, [Browser::new(BrowserKind::Chrome, Some(123.0))])?;

client.add_data(
    visitor_code,
    [
        PageView::new("https://example.com/pricing".to_owned(), Some("Pricing".to_owned()), vec![3]).into(),
        UserAgent::new("Mozilla/5.0".to_owned()).into(),
    ],
)?;

client.add_data_with_track(
    visitor_code,
    vec![PageView::new("https://example.com/checkout".to_owned(), Some("Checkout".to_owned()), vec![])],
    false,
)?;
```

##### Parameters

| Name                                                         | Type                                                 | Description                                                                                                                                                                                  | Default value |
| ------------------------------------------------------------ | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str`                                               | Unique identifier of the visitor.                                                                                                                                                            |               |
| `data` <Badge color="red" size="sm">required</Badge>         | `impl IntoIterator<Item = impl Into<KameleoonData>>` | Collection of Kameleoon data types.                                                                                                                                                          |               |
| `track` <Badge color="green" size="sm">optional</Badge>      | `bool`                                               | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |

##### Return value

| Type                         | Description                                                         |
| ---------------------------- | ------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether data was successfully added or an error occurred. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### flush()

* *📨 Sends tracking data to Kameleoon*

The `flush()` method aggregates all Kameleoon data associated with a visitor and sends a tracking request to the server. This request includes any data previously added via the [`add_data`](#add_data) method that has not yet been transmitted through other tracking mechanisms (see the referenced methods for details). The `flush()` operation is non-blocking, as the server call is performed asynchronously.

This method provides control over when data linked to a specific `visitor_code` is transmitted. For example, if `add_data()` is called multiple times, sending a request after each invocation would be inefficient. Instead, you can batch these updates and call `flush()` once to send all accumulated data in a single request.

The `flush()` method uses the provided `visitor_code` as the unique visitor identifier.

<Tip>
  * `flush()` — Queues a flush operation according to the configured tracking interval.
  * `flush_instant()` — Sends tracking data immediately without waiting for the interval.
</Tip>

```rust theme={null}
// Queues a flush operation for the given visitor_code.
// Data will be sent according to the configured tracking interval (non-blocking).
client.flush(visitor_code)?;

// Immediately sends all pending tracking data for the given visitor_code.
// This is an async operation and must be awaited.
client.flush_instant(visitor_code).await?;
```

##### Parameters

| Name                                                         | Type   | Description                       |
| ------------------------------------------------------------ | ------ | --------------------------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str` | Unique identifier of the visitor. |

##### Return value

| Type                         | Description                                                                                      |
| ---------------------------- | ------------------------------------------------------------------------------------------------ |
| `Result<(), KameleoonError>` | Indicates whether the operation was successfully scheduled or executed, or if an error occurred. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### get\_remote\_data()

The `get_remote_data()` method lets you retrieve remote data stored on Kameleoon servers for the specified `key`. In most setups, this data is written through the Kameleoon Data API and can later be fetched by your Rust service whenever you need additional application context.

This method is useful when you want to keep structured information on Kameleoon's remote infrastructure and reuse it from your back-end without maintaining a separate retrieval mechanism.

```rust theme={null}
let data = client.get_remote_data("test-key").await?;
```

##### Parameters

| Name                                                | Type   | Description                                               |
| --------------------------------------------------- | ------ | --------------------------------------------------------- |
| `key` <Badge color="red" size="sm">required</Badge> | `&str` | Key associated with the remote data you want to retrieve. |

##### Return value

| Type                             | Description                                                                                                                            |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `Result<String, KameleoonError>` | Payload associated with the specified `key` on success, otherwise an error. In most cases, the payload is JSON serialized as a string. |

##### Errors

| Type                        | Description                                                                                        |
| --------------------------- | -------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization` | Indicates that the SDK is not yet fully initialized.                                               |
| `ErrorCode::Network`        | Returned when the remote data request fails or the server responds with a non-success status code. |

#### get\_remote\_visitor\_data()

`get_remote_visitor_data()` is an asynchronous method for retrieving Kameleoon visit data for the provided `visitor_code`. The method adds the data to local visitor storage so other SDK methods can use it for targeting decisions.

Data obtained using this method is especially useful when you want to:

* use data collected from other devices.
* access a visitor's history, such as previously viewed pages from past visits.
* use data that is only available on the client side, such as datalayer variables and front-end goal conversions.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  By default, `get_remote_visitor_data()` automatically retrieves the latest stored custom data with `scope=Visitor` and attaches it to the visitor without the need to call [`add_data()`](#add_data). This is especially useful for [synchronizing custom data across multiple devices](/developer-docs/cross-device-experimentation/).
</Warning>

```rust theme={null}
use kameleoon_client::types::RemoteVisitorDataFilter;

// Fetch remote visitor data without any filter
// This will return all available data for the given visitor
client.get_remote_visitor_data(visitor_code, None).await?;

// Create a filter to limit the returned data
let filter = RemoteVisitorDataFilter {
    // Include data from the last 5 visits
    previous_visit_amount: 5,
    // Include conversion events (e.g., goals, transactions)
    conversions: true,
    // Include page view history
    page_views: true,
    // Use default values for all other fields
    ..Default::default()
};

// Fetch remote visitor data using the specified filter
// This will return only the data matching the filter criteria
client.get_remote_visitor_data(visitor_code, Some(filter)).await?;
```

##### Parameters

| Name                                                         | Type                              | Description                                                      | Default                              |
| ------------------------------------------------------------ | --------------------------------- | ---------------------------------------------------------------- | ------------------------------------ |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str`                            | Visitor code whose data should be fetched.                       |                                      |
| `filter` <Badge color="green" size="sm">optional</Badge>     | `Option<RemoteVisitorDataFilter>` | Filter describing which remote visitor data should be retrieved. | `RemoteVisitorDataFilter::default()` |

##### Return value

| Type                         | Description                                                                          |
| ---------------------------- | ------------------------------------------------------------------------------------ |
| `Result<(), KameleoonError>` | Returns successfully when the data is fetched and added locally, otherwise an error. |

##### Errors

| Type                            | Description                                                                                                                   |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                          |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.           |
| `ErrorCode::Network`            | Returned when the remote visitor data request fails, cannot be parsed, or the server responds with a non-success status code. |

##### Using parameters in get\_remote\_visitor\_data()

The `get_remote_visitor_data()` method lets you control which data is retrieved for a visitor. The same filtering approach works across goals, experiments, variations, and other visitor data.

For example, if you want to target users who converted on a goal during their last five visits, you can set `previous_visit_amount` to `5` and `conversions` to `true`.

The flexibility shown in this example is not limited to goal data. You can use the filter to retrieve many different visitor behaviors and make them available to targeting and reporting logic in your Rust application.

##### `RemoteVisitorDataFilter` fields

| Name                    | Type   | Description                                                   | Default |
| ----------------------- | ------ | ------------------------------------------------------------- | ------- |
| `previous_visit_amount` | `u32`  | Number of previous visits to retrieve data from.              | `1`     |
| `current_visit`         | `bool` | If `true`, current visit data will be retrieved.              | `true`  |
| `custom_data`           | `bool` | If `true`, custom data will be retrieved.                     | `true`  |
| `visitor_code`          | `bool` | If `true`, the most recent visitor code will be reused.       | `true`  |
| `page_views`            | `bool` | If `true`, page view data will be retrieved.                  | `false` |
| `geolocation`           | `bool` | If `true`, geolocation data will be retrieved.                | `false` |
| `device`                | `bool` | If `true`, device data will be retrieved.                     | `false` |
| `browser`               | `bool` | If `true`, browser data will be retrieved.                    | `false` |
| `operating_system`      | `bool` | If `true`, operating system data will be retrieved.           | `false` |
| `conversions`           | `bool` | If `true`, conversion data will be retrieved.                 | `false` |
| `experiments`           | `bool` | If `true`, experiment data will be retrieved.                 | `false` |
| `kcs`                   | `bool` | If `true`, Kameleoon Conversion Score data will be retrieved. | `false` |
| `personalizations`      | `bool` | If `true`, personalization data will be retrieved.            | `false` |
| `cbs`                   | `bool` | If true, Contextual Bandit score data will be retrieved.      | `false` |

#### get\_visitor\_warehouse\_audience()

This method retrieves audience data associated with a visitor in your warehouse integration by using the specified `visitor_code` and, optionally, a `warehouse_key`. The `warehouse_key` is typically your internal user ID. The `custom_data_index` parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors.

When the call succeeds, the SDK converts the returned audience list into [`CustomData`](#customdata), adds it to the visitor locally, and makes it available for targeting purposes. For more background, see the [warehouse targeting documentation](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting).

```rust theme={null}
// Fetch audience data for a visitor using only the visitor_code.
client.get_visitor_warehouse_audience(visitor_code, None, 98).await?;

// Fetch audience data for a visitor using both visitor_code and warehouse_key.
// Useful when your warehouse uses a different identifier than visitor_code.
client.get_visitor_warehouse_audience(visitor_code, Some("internal-user-id"), 98).await?;
```

##### Parameters

| Name                                                              | Type           | Description                                                                 | Default        |
| ----------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------- | -------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge>      | `&str`         | Visitor whose warehouse audiences should be retrieved.                      |                |
| `warehouse_key` <Badge color="green" size="sm">optional</Badge>   | `Option<&str>` | External warehouse key, usually your internal user ID.                      | `visitor_code` |
| `custom_data_index` <Badge color="red" size="sm">required</Badge> | `u32`          | Custom data index configured in Kameleoon for warehouse audience targeting. |                |

##### Return value

| Type                         | Description                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Success when the warehouse audience data is retrieved and stored locally as `CustomData`. |

##### Errors

| Type                            | Description                                                                                                                  |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                         |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.          |
| `ErrorCode::Network`            | Returned when the warehouse audience request fails, cannot be parsed, or the server responds with a non-success status code. |

#### set\_legal\_consent()

You must use this method to specify whether the visitor has given legal consent to use personal data. Setting `legal_consent` to `false` limits the types of data that can be included in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. For more information, see the [consent management policy](/user-manual/project-management/consent-management-policy).

If you provide a cookie accessor, the SDK also updates the visitor cookies according to the consent status.

```rust theme={null}
// Set consent and update cookies
client.set_legal_consent(visitor_code, true, Some(&mut cookies))?;

// Set consent without updating cookies
client.set_legal_consent(visitor_code, true, None)?;
```

##### Parameters

| Name                                                          | Type                               | Description                                                                                                                              | Default |
| ------------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge>  | `&str`                             | The user's unique identifier.                                                                                                            |         |
| `legal_consent` <Badge color="red" size="sm">required</Badge> | `bool`                             | `true` indicates the visitor has given legal consent, `false` indicates the visitor has never provided, or has withdrawn, legal consent. |         |
| `cookies` <Badge color="green" size="sm">optional</Badge>     | `Option<&mut impl CookieAccessor>` | Optional cookie accessor used to update cookies.                                                                                         | `None`  |

##### Return value

| Type                         | Description                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether the visitor consent state was updated successfully, otherwise an error. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

##### Consent revocation behavior

When you call `set_legal_consent()` with `legal_consent=false`, the SDK does not delete the `kameleoonVisitorCode` cookie. Instead, it stops extending the cookie's expiration date, allowing the cookie to persist until it naturally expires.

If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.

### Goals and third-party analytics

#### track\_conversion()

* 📨 *Sends Tracking Data to Kameleoon*

Use this method to track a conversion for a specific [goal](/user-manual/assets/goals/create-a-goal) and user. This method requires `visitor_code` and `goal_id`. In addition, this method also accepts an optional `revenue`, `negative` and `metadata` arguments. The `visitor_code` is usually identical to the one that was used when triggering the experiment.

<Tip>
  This method is non-blocking as the server call is made asynchronously.
</Tip>

```rust theme={null}
use kameleoon_client::client::TrackConversionOpts;
use kameleoon_client::data::CustomData;

// Track a goal
client.track_conversion(visitor_code, goal_id)?;

// Track a goal with revenue
client.track_conversion_with_opts(visitor_code, goal_id, TrackConversionOpts::new().revenue(100.0))?;

// Track a goal with negative revenue
client.track_conversion_with_opts(
    visitor_code,
    goal_id,
    TrackConversionOpts::new().revenue(100.0).negative(true)
)?;

// Track a goal with custom metadata
client.track_conversion_with_opts(
    visitor_code,
    goal_id,
    TrackConversionOpts::new().metadata(vec![CustomData::new(4, vec!["true".to_owned()])]),
)?;
```

##### Parameters

| Name                                                         | Type              | Description                                                                                                                      | Default  |
| ------------------------------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str`            | Unique identifier of the visitor.                                                                                                |          |
| `goal_id` <Badge color="red" size="sm">required</Badge>      | `u32`             | ID of the goal.                                                                                                                  |          |
| `revenue` <Badge color="green" size="sm">optional</Badge>    | `f32`             | Revenue of the conversion.                                                                                                       | `0`      |
| `negative` <Badge color="green" size="sm">optional</Badge>   | `bool`            | Defines if the revenue is positive or negative.                                                                                  | `false`  |
| `metadata` <Badge color="green" size="sm">optional</Badge>   | `Vec<CustomData>` | Metadata of the conversion. [Must be defined beforehand in the Kameleoon App](/user-manual/assets/goals/create-a-goal#metadata). | `vec![]` |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  If the `metadata` parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the [`add_data()`](#add_data) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#customdata) prior to the conversion and within the same visit.

  Kameleoon will only consider the metadata values that are explicitly passed as parameters to the `track_conversion()` method.

  In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value 'Amex Credit Card').

  ```rust theme={null}
  client.add_data(
      visitor_code,
      [
          CustomData::new(5, vec!["Credit Card".to_owned()]),
          CustomData::new(9, vec!["Express Delivery".to_owned()])
      ]
  )?;

  client.track_conversion_with_opts(
      visitor_code,
      goal_id,
      TrackConversionOpts::new().metadata(vec![CustomData::new(5, vec!["Amex Credit Card".to_owned()])]),
  )?
  ```
</Note>

##### Return value

| Type                         | Description                                                                                             |
| ---------------------------- | ------------------------------------------------------------------------------------------------------- |
| `Result<(), KameleoonError>` | Indicates whether the conversion was successfully queued for asynchronous tracking, otherwise an error. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### get\_engine\_tracking\_code()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the `get_engine_tracking_code()` method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.

Refer to [hybrid experimentation](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) for more information on implementing this method.

```rust theme={null}
let tracking_code = client.get_engine_tracking_code(visitor_code)?;
```

<Note>
  * To use this feature, implement both the Rust SDK and Kameleoon [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation). Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing `</body>` tag.
  * If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the [JavaScript / TypeScript SDK](/developer-docs/sdks/web-sdks/js-sdk). This option works well for [serverless edge compute platforms](/developer-docs/feature-experimentation/implementation-and-deployment/serverless-edge-compute-starter-kits). The JavaScript / TypeScript SDK automatically tracks variations when you call [`getVisitorCode`](/developer-docs/sdks/web-sdks/js-sdk#getvisitorcode), as long as you add the corresponding experiment assignments to `window.kameleoonQueue`.
  * You can insert the returned tracking code directly into an HTML `<script>` tag.

  ```html theme={null}
  <html lang="en">
    <body>
      <script>
        const engineTrackingCode = `
          window.kameleoonQueue = window.kameleoonQueue || [];
          window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
          window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
        `;
        const script = document.createElement('script');

        script.textContent = engineTrackingCode;
        document.body.appendChild(script);
      </script>

    </body>
  </html>
  ```

  In this example, `123456` and `234567` are experiment IDs, and `7890` and `8901` are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
</Note>

##### Parameters

| Name                                                         | Type   | Description                       |
| ------------------------------------------------------------ | ------ | --------------------------------- |
| `visitor_code` <Badge color="red" size="sm">required</Badge> | `&str` | Unique identifier of the visitor. |

##### Return value

| Type                             | Description                                                              |
| -------------------------------- | ------------------------------------------------------------------------ |
| `Result<String, KameleoonError>` | JavaScript code to insert into the page on success; otherwise, an error. |

##### Errors

| Type                            | Description                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode::Initialization`     | Indicates that the SDK is not yet fully initialized.                                                                |
| `ErrorCode::VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

### Events

#### on\_datafile\_update()

The `on_datafile_update()` method allows you to handle datafile update events. It accepts a single parameter, **handler**, which is called whenever the configuration is updated through either [polling](https://docs.kameleoon.com/developer-docs/feature-experimentation/technical-reference/technical-considerations#polling-default) or [streaming](https://docs.kameleoon.com/developer-docs/feature-experimentation/technical-reference/technical-considerations#streaming-premium-option) datafile update events.

```rust theme={null}
// Register a callback that is invoked whenever the configuration
// is updated through a polling or streaming datafile update event.
client.on_datafile_update(Some(Box::new(|| {
    // Custom logic to execute after the datafile has been updated.
    println!("Kameleoon datafile updated");
})));

// Unregister the datafile update callback.
// No callback will be invoked for future datafile updates.
client.on_datafile_update(None);
```

##### Parameters

| Name      | Type                                  | Description                                                        |
| --------- | ------------------------------------- | ------------------------------------------------------------------ |
| `handler` | `Option<Box<dyn Fn() + Send + Sync>>` | The handler that will be called when the configuration is updated. |

### Data types

This section lists the Rust data types re-exported by the SDK in `kameleoon_client::data`.

#### ApplicationVersion

`ApplicationVersion` represents the semantic version number of your application.

<Tip>
  A **visitor** can have only one `ApplicationVersion`. Adding a second instance will overwrite the first one.
</Tip>

| Name                                                    | Type   | Description                                                                                                                                      |
| ------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| version <Badge color="green" size="sm">optional</Badge> | `&str` | The mobile application version. This field must follow semantic versioning. Accepted formats are `major`, `major.minor`, or `major.minor.patch`. |

```rust theme={null}
use kameleoon_client::data::ApplicationVersion;

// major
client.add_data(visitor_code, [ApplicationVersion::new("10")])?;
// major.minor
client.add_data(visitor_code, [ApplicationVersion::new("10.20")])?;
// major.minor.patch
client.add_data(visitor_code, [ApplicationVersion::new("10.20.30")])?;
```

#### Browser

The `Browser` data set stored here can be used to filter experiment and personalization reports by any value associated with it.

| Name                                                      | Type          | Description                                                                                                                                                          |
| --------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kind` <Badge color="red" size="sm">required</Badge>      | `BrowserKind` | List of browsers: `BrowserKind::Chrome`, `BrowserKind::InternetExplorer`, `BrowserKind::Firefox`, `BrowserKind::Safari`, `BrowserKind::Opera`, `BrowserKind::Other`. |
| `version` <Badge color="green" size="sm">optional</Badge> | `Option<f32>` | Version of the browser, floating point number represents major and minor version of the browser                                                                      |

```rust theme={null}
use kameleoon_client::data::{Browser, BrowserKind};

// Browser data with a version
client.add_data(visitor_code, [Browser::new(BrowserKind::Safari, 26.4)])?;
// Browser data without a version
client.add_data(visitor_code, [Browser::new(BrowserKind::Chrome, None)])?;
```

#### Conversion

The `Conversion` data set stored here can be used to filter experiment and personalization reports by any goal associated with it.

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goal_id` in the Kameleoon app.
</Tip>

| Name                                                       | Type              | Description                                     | Default  |
| ---------------------------------------------------------- | ----------------- | ----------------------------------------------- | -------- |
| `goal_id` <Badge color="red" size="sm">required</Badge>    | `u32`             | ID of the goal.                                 |          |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `f32`             | Revenue of the conversion                       | `0`      |
| `negative` <Badge color="green" size="sm">optional</Badge> | `bool`            | Defines if the revenue is positive or negative. | `false`  |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `Vec<CustomData>` | Metadata of the conversion.                     | `vec![]` |

```rust theme={null}
use kameleoon_client::data::{Conversion, ConversionOpts, CustomData};

// Add a simple conversion with ID 32
client.add_data(visitor_code, [Conversion::new(32)])?;

// Add conversion with ID 33 including revenue and marked as negative
client.add_data(visitor_code, [Conversion::new_with_opts(33, ConversionOpts::new().revenue(10.0).negative(true))])?;

// Add conversion with ID 34 including revenue, negative flag, and custom metadata
client.add_data(
    visitor_code,
    [
        Conversion::new_with_opts(
            34,
            ConversionOpts::new().revenue(10.0).negative(true).metadata(vec![
                CustomData::new(3, vec!["metadata1".to_owned(), "md2".to_owned()]),
                CustomData::new(5, vec!["md3".to_owned()]),
            ]),
        )
    ],
)?;
```

#### Cookie

`Cookie` contains information about the cookies stored on the visitor's device.

| Name    | Type                      | Description                                     |
| ------- | ------------------------- | ----------------------------------------------- |
| cookies | `HashMap<String, String>` | A string map containing cookie keys and values. |

<Tip>
  Each visitor can only have one `Cookie`. Adding a second `Cookie` overwrites the first one.
</Tip>

```rust theme={null}
use std::collections::HashMap;
use kameleoon_client::data::Cookie;

client.add_data(visitor_code, [Cookie::new(HashMap::from([("segment".to_owned(), "vip".to_owned())]))])?;
```

#### CustomData

`CustomData` enables the association of any type of data with each visitor, making it an effective tool for targeting conditions in [segments](/user-manual/assets/segments/create-a-segment/). Additionally, it can be used as a filter or breakdown in experiment reports. For more information about custom data, please refer to this [article](/developer-docs/custom-data).

Define custom data types in the Kameleoon app or the Data API and use them from the SDK.

| Name                                                      | Type           | Description                                                                                                                                                                             | Default |
| --------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| index/name <Badge color="red" size="sm">required</Badge>  | `u32`/`String` | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |         |
| values <Badge color="red" size="sm">required</Badge>      | `Vec<String>`  | Values of the custom data to be stored.                                                                                                                                                 |         |
| overwrite <Badge color="green" size="sm">optional</Badge> | `bool`         | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true`  |

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`(`name`). Adding another `CustomData` with the same `index`(`name`) will replace the existing one.

  * The custom data ‘index’ can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) under the “INDEX” column.

  * To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: **Use this data only locally for targeting purposes** when creating custom data.

  * Adding a `CustomData` instance created with a name when the SDK instance is not initialized or the name is not registered, will result in the data being ignored.
</Note>

```rust theme={null}
use kameleoon_client::data::{CustomData, CustomDataOpts};

client.add_data(visitor_code, [CustomData::new_with_index(1, vec!["value".to_owned()])])?;

// With several values
client.add_data(
    visitor_code,
    [CustomData::new_with_index(
        1,
        vec!["value1".to_owned(), "value2".to_owned()],
    )],
)?;

// To set the `overwrite` flag to false
client.add_data(
    visitor_code,
    [CustomData::new_with_index_opts(
        1,
        vec!["value".to_owned()],
        CustomDataOpts::new().overwrite(false),
    )],
)?;

// To use a name instead of the index
client.add_data(
    visitor_code,
    [CustomData::new_with_name(
        "my-custom-data".to_owned(),
        vec!["value".to_owned()],
    )],
)?;

// To use a name instead of the index and set the `overwrite` flag to false
client.add_data(
    visitor_code,
    [CustomData::new_with_name_opts(
        "my-custom-data",
        vec!["value".to_owned()],
        CustomDataOpts::new().overwrite(false),
    )],
)?;
```

#### Device

You can use device data to filter experiment and personalization reports by any associated value.

| Name | Type         | Description                                                        |
| ---- | ------------ | ------------------------------------------------------------------ |
| kind | `DeviceKind` | Device type. Possible values are `Phone`, `Tablet`, and `Desktop`. |

```rust theme={null}
use kameleoon_client::data::{Device, DeviceKind};

client.add_data(visitor_code, [Device::new(DeviceKind::Desktop)])?;
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Name                                                          | Type                          | Description                                                                                                      |
| ------------------------------------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>       | `&str`                        | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>      | <nobr>`Option<String>`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>        | <nobr>`Option<String>`</nobr> | The city of the visitor.                                                                                         |
| `postal_code` <Badge color="green" size="sm">optional</Badge> | <nobr>`Option<String>`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>    | `Option<f32>`                 | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>   | `Option<f32>`                 | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```rust theme={null}
use kameleoon_client::data::GeolocationBuilder;

let geolocation = GeolocationBuilder::default()
    .country("France")
    .region("Ile-de-France".to_owned())
    .city("Paris".to_owned())
    .postal_code("75009".to_owned())
    .latitude(48.8720171)
    .longitude(2.3338352)
    .build()
    .unwrap();

client.add_data(visitor_code, [geolocation])?;
```

#### OperatingSystem

`OperatingSystem` contains information about the operating system on the visitor's device.

| Name | Type                  | Description                                                                                                   |
| ---- | --------------------- | ------------------------------------------------------------------------------------------------------------- |
| kind | `OperatingSystemKind` | Operating system family. Possible values are `Windows`, `Mac`, `IOS`, `Linux`, `Android`, and `WindowsPhone`. |

<Tip>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first one.
</Tip>

```rust theme={null}
use kameleoon_client::data::{OperatingSystem, OperatingSystemKind};

client.add_data(visitor_code, [OperatingSystem::new(OperatingSystemKind::Windows)])?;
```

#### PageView

Store page view events.

| Name      | Type             | Description                                  | Default  |
| --------- | ---------------- | -------------------------------------------- | -------- |
| url       | `String`         | URL of the page viewed.                      |          |
| title     | `Option<String>` | Title of the page viewed.                    | `None`   |
| referrers | `Vec<u32>`       | Referrer indices of previously viewed pages. | `vec![]` |

<Note>
  The referrer index is available in the Kameleoon app on the [acquisition channel configuration](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) page. Be careful: the index starts at `0`, so the first acquisition channel you create has the ID `0`, not `1`.
</Note>

```rust theme={null}
use kameleoon_client::data::{PageView, PageViewOpts};

// new() - full constructor with url, optional title, and referrers
client.add_data(visitor_code, [PageView::new("https://example.com", Some("Homepage"), vec![3])])?;

// new_with_url() - minimal constructor, only requires a URL
client.add_data(visitor_code, [PageView::new_with_url("https://example.com")])?;

// new_with_opts() - constructor using PageViewOpts builder for optional fields
let opts = PageViewOpts::builder().title("Homepage").referrers(vec![3]).build();
client.add_data(visitor_code, [PageView::new_with_opts("https://example.com", opts)])?;
```

#### UniqueIdentifier

If you do not add `UniqueIdentifier` for a visitor, `visitor_code` is used as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/cross-device-experimentation/). When you add `UniqueIdentifier::new(true)`, the SDK links flushed data with the visitor associated with the specified identifier.

This can be useful in situations where you cannot access the anonymous `visitor_code` originally assigned to a visitor, but you do have access to an internal identifier connected to that visitor through session merging.

| Name    | Type   | Description                                                                  |
| ------- | ------ | ---------------------------------------------------------------------------- |
| `value` | `bool` | Whether the current `visitor_code` should be treated as a unique identifier. |

```rust theme={null}
use kameleoon_client::data::UniqueIdentifier;

client.add_data(visitor_code, [UniqueIdentifier::new(true)])?;
```

#### UserAgent

Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to recognize known bots and spiders, and it also uses the `UserAgent` field to filter out other unwanted traffic that might distort your conversion metrics. For more information, see the help article on [bot filtering](/user-manual/faq#how-does-kameleoon-filter-bot-traffic-from-my-results).

If you use internal bots, we recommend sending the user-agent value `curl/8.0` to exclude them from analytics.

| Name  | Type     | Description                                   |
| ----- | -------- | --------------------------------------------- |
| value | `String` | User-Agent value sent with tracking requests. |

```rust theme={null}
use kameleoon_client::data::UserAgent;

client.add_data(visitor_code, [UserAgent::new("Mozilla/5.0")])?;
```

### Returned types

#### DataFile

The `DataFile` contains the SDK configuration details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name            | Type                             | Description                                                                       |
| --------------- | -------------------------------- | --------------------------------------------------------------------------------- |
| `feature_flags` | `HashMap<Arc<str>, FeatureFlag>` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `date_modified` | `u64`                            | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```rust theme={null}
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
let feature_flags: &HashMap<Arc<str>, FeatureFlag> = &datafile.feature_flags;

// Retrieves the last modification timestamp of the DataFile.
// The value is a u64 representing milliseconds since the Unix epoch.
let date_modified: u64 = datafile.date_modified;
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), environment status, and other related details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name                    | Type                           | Description                                                                |
| ----------------------- | ------------------------------ | -------------------------------------------------------------------------- |
| `environment_enabled`   | `bool`                         | Indicating whether the feature flag is enabled in the current environment. |
| `default_variation_key` | `&str`                         | The key of the default variation associated with the feature flag.         |
| `variations`            | `HashMap<Arc<str>, Variation>` | A map of `Variation` objects, keyed by variation keys.                     |
| `rules`                 | `Vec<Rule>`                    | A list of `Rule` objects                                                   |

```rust theme={null}
// Check whether the feature flag is enabled in the current environment.
let environment_enabled: bool = feature_flag.environment_enabled;

// Retrieve the key of the default variation.
let default_variation_key: &str = feature_flag.default_variation_key.as_ref();

// Retrieve the default variation object.
let default_variation: &Variation = feature_flag.default_variation();

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object).
let variations: &HashMap<Arc<str>, Variation> = &feature_flag.variations;

// Retrieve all targeting rules associated with the feature flag.
let rules: &Vec<Rule> = &feature_flag.rules;
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                           | Description                                            |
| ------------ | ------------------------------ | ------------------------------------------------------ |
| `variations` | `HashMap<Arc<str>, Variation>` | A map of `Variation` objects, keyed by variation keys. |

```rust theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
let variations: &HashMap<Arc<str>, Variation> = &rule.variations;
```

#### Variation

`Variation` contains information about the visitor's assigned variation, or the default variation when no specific assignment exists.

| Name           | Type            | Description                                                                                           |
| -------------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| name           | `Arc<str>`      | The name of the variation.                                                                            |
| key            | `Arc<str>`      | The unique key identifying the variation.                                                             |
| id             | `Option<u32>`   | The ID of the assigned variation, or `None` for a default variation.                                  |
| experiment\_id | `Option<u32>`   | The ID of the experiment associated with the variation, or `None` for a default variation.            |
| variables      | `Vec<Variable>` | Variables associated with the variation. This collection can be empty when no variables are attached. |

<Note>
  * `Variation` describes the assigned or default variation, while [`Variable`](#variable) contains the details of each individual variable.
  * `id` and `experiment_id` can be `None`, which indicates a default variation that is not tied to a specific experiment assignment.
</Note>

Additional helper methods:

| Method              | Return type         | Description                              |
| ------------------- | ------------------- | ---------------------------------------- |
| `is_active()`       | `bool`              | Returns `false` for the `off` variation. |
| `get_variable(key)` | `Option<&Variable>` | Returns a variation variable by key.     |

```rust theme={null}
// Retrieving the variation name
let variation_name: &str = variation.name.as_ref();

// Retrieving the variation key
let variation_key: &str = variation.key.as_ref();

// Retrieving the variation id
let variation_id = variation.id;

// Retrieving the experiment id
let experiment_id = variation.experiment_id;

// Retrieving the variables `Vec`
let variables = &variation.variables;

// Checking if the variation is active (i.e., currently being served to visitors)
let is_active = variation.is_active();

// Retrieving a variable by its key, returning `None` if not found
let variable = variation.get_variable("title")?;
```

#### Variable

`Variable` contains information about a variable associated with the assigned variation.

| Name  | Type                      | Description                                                                                                                             |
| ----- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| key   | `Arc<str>`                | The unique key identifying the variable.                                                                                                |
| kind  | `Arc<str>`                | The variable type. Possible values include `BOOLEAN`, `NUMBER`, `STRING`, `JSON`, `JS`, and `CSS`.                                      |
| value | [`JsonValue`](#jsonvalue) | The value of the variable. Depending on `kind`, it can hold a boolean, number, string, JSON string, JavaScript snippet, or CSS snippet. |

```rust theme={null}
use kameleoon_client::types::JsonValue;

// Retrieve the list of variables associated with the variation
let variables = &variation.variables;

// Access the variable key
let variable_key: &str = variable.key.as_ref();

// Access the variable type (kind) for conditional handling
let kind: &str = variable.kind.as_ref();

// Extract the value as a number (returns `None` if not a number)
let number: Option<f64> = variable.value.as_number();

// Extract the value as a boolean (returns `None` if not a boolean)
let apply_discount: Option<bool> = variable.value.as_bool();

// Extract the value as a string slice (returns `None` if not a string)
let title: Option<&str> = variable.value.as_str();
```

##### JsonValue

`JsonValue` represents the value of a variation variable in Rust.

| Value                         | Description                           |
| ----------------------------- | ------------------------------------- |
| `JsonValue::Boolean(bool)`    | Represents a boolean value.           |
| `JsonValue::Number(f64)`      | Represents a numeric value.           |
| `JsonValue::String(Arc<str>)` | Represents a string value.            |
| `JsonValue::Json(Arc<str>)`   | Represents a JSON-encoded value.      |
| `JsonValue::Js(Arc<str>)`     | Represents a JavaScript code snippet. |
| `JsonValue::Css(Arc<str>)`    | Represents a CSS code snippet.        |

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `1.0.0`.
</Warning>

#### get\_feature\_keys()

<Tip>
  If you want to iterate over all feature flags and call [`get_variation()`](#get_variation) on each, use the [`get_variations()`](#get_variations) method instead.
</Tip>

Returns a list of feature flag keys currently available for the SDK.

```rust theme={null}
let feature_keys = client.get_feature_keys()?;
```

##### Return value

| Type                                  | Description                                               |
| ------------------------------------- | --------------------------------------------------------- |
| `Result<Vec<String>, KameleoonError>` | List of feature flag keys on success, otherwise an error. |

##### Errors

| Type                        | Description                                          |
| --------------------------- | ---------------------------------------------------- |
| `ErrorCode::Initialization` | Indicates that the SDK is not yet fully initialized. |
