From 83204275b4815c4492a8452a20314abd0d8fe427 Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Tue, 11 Jun 2024 17:45:26 +0200 Subject: [PATCH 1/8] Add docs for Rust SDK --- website/docs/sdk-reference/android.mdx | 4 +- website/docs/sdk-reference/go.mdx | 2 +- website/docs/sdk-reference/java.mdx | 4 +- website/docs/sdk-reference/ruby.mdx | 2 +- website/docs/sdk-reference/rust.mdx | 689 ++++++++++++++++++ website/docusaurus.config.ts | 3 +- website/sidebars.ts | 1 + website/src/pages/index.js | 1 + .../version-V1/sdk-reference/android.mdx | 2 +- .../version-V1/sdk-reference/go.mdx | 2 +- .../version-V1/sdk-reference/java.mdx | 2 +- .../version-V1/sdk-reference/ruby.mdx | 2 +- .../version-V1/sdk-reference/rust.mdx | 689 ++++++++++++++++++ .../version-V1-sidebars.json | 5 + 14 files changed, 1397 insertions(+), 11 deletions(-) create mode 100644 website/docs/sdk-reference/rust.mdx create mode 100644 website/versioned_docs/version-V1/sdk-reference/rust.mdx diff --git a/website/docs/sdk-reference/android.mdx b/website/docs/sdk-reference/android.mdx index b4c4ff14..80ac3d16 100644 --- a/website/docs/sdk-reference/android.mdx +++ b/website/docs/sdk-reference/android.mdx @@ -109,7 +109,7 @@ These are the available options on the `Options` class: | Options | Description | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataGovernance(DataGovernance)` | Optional, defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `baseUrl(string)` | _Obsolete_ Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | +| `baseUrl(string)` | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | | `httpClient(OkHttpClient)` | Optional, sets the underlying `OkHttpClient` used to download the feature flags and settings over HTTP. [More about the HTTP Client](#httpclient). | | `cache(ConfigCache)` | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache). | | `pollingMode(PollingMode)` | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes). | @@ -635,7 +635,7 @@ Call the `forceRefresh()` method on the client to download the latest config JSO ## Logging -As the SDK uses the facade of [slf4j](https://www.slf4j.org) for logging, so you can use any of the slf4j implementation packages. +The SDK uses the facade of [slf4j](https://www.slf4j.org) for logging, so you can use any of the slf4j implementation packages. You can change the verbosity of the logs by passing a `LogLevel` parameter to the ConfigCatClientBuilder's `logLevel` function. diff --git a/website/docs/sdk-reference/go.mdx b/website/docs/sdk-reference/go.mdx index e5707391..23c53dae 100644 --- a/website/docs/sdk-reference/go.mdx +++ b/website/docs/sdk-reference/go.mdx @@ -85,7 +85,7 @@ Available optional properties: | ------------------ | -------------------------- | ------------ | | `SDKKey` | `string` | SDK Key to access your feature flags and configurations. Get it from _ConfigCat Dashboard_. | | `DataGovernance` | `configcat.DataGovernance` | Defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `BaseUrl` | `string` | _Obsolete_ Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `BaseUrl` | `string` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | | `Cache ` | `ConfigCache` | Sets a custom cache implementation for the client. [See below](#custom-cache). | | `NoWaitForRefresh` | `bool` | Defaults to `false`. When it's `true` the typed get methods (`Get[TYPE]Value()`) will never wait for a configuration refresh to complete before returning. When it's `false` and `PollingMode` is `AutoPoll`, the first request may block, when `PollingMode` is `Lazy`, any request may block. | | `HttpTimeout` | `time.Duration` | Sets the maximum wait time for a HTTP response. [More about the HTTP timeout](#http-timeout) | diff --git a/website/docs/sdk-reference/java.mdx b/website/docs/sdk-reference/java.mdx index 8c3c5bec..6b0356ed 100644 --- a/website/docs/sdk-reference/java.mdx +++ b/website/docs/sdk-reference/java.mdx @@ -114,7 +114,7 @@ These are the available options on the `Options` class: | Option | Description | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataGovernance(DataGovernance)` | Optional, defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `baseUrl(string)` | _Obsolete_ Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `baseUrl(string)` | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | | `httpClient(OkHttpClient)` | Optional, sets the underlying `OkHttpClient` used to download the feature flags and settings over HTTP. [More about the HTTP Client](#httpclient). | | `cache(ConfigCache)` | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache). | | `pollingMode(PollingMode)` | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes). | @@ -835,7 +835,7 @@ Call the `forceRefresh()` method on the client to download the latest config JSO ## Logging -As the SDK uses the facade of [slf4j](https://www.slf4j.org) for logging, so you can use any of the slf4j implementation packages. +The SDK uses the facade of [slf4j](https://www.slf4j.org) for logging, so you can use any of the slf4j implementation packages. You can change the verbosity of the logs by passing a `LogLevel` parameter to the ConfigCatClientBuilder's `logLevel` function. diff --git a/website/docs/sdk-reference/ruby.mdx b/website/docs/sdk-reference/ruby.mdx index c77b034c..ac8a54d8 100644 --- a/website/docs/sdk-reference/ruby.mdx +++ b/website/docs/sdk-reference/ruby.mdx @@ -68,7 +68,7 @@ _ConfigCat Client_ is responsible for: | Client options | Description | Default | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| `base_url` | _Obsolete_, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | nil | +| `base_url` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | nil | | `polling_mode` | Sets the polling mode for the client. [More about polling modes](#polling-modes). | PollingMode.auto_poll | | `config_cache` | Sets a custom config cache implementation for the client. [More about cache](#custom-cache). | nil | | `proxy_address` | Sets custom proxy address for the client. [More about proxy](#using-configcat-behind-a-proxy). | nil | diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx new file mode 100644 index 00000000..fe52ae72 --- /dev/null +++ b/website/docs/sdk-reference/rust.mdx @@ -0,0 +1,689 @@ +--- +id: rust +title: Rust SDK Reference +description: ConfigCat Rust SDK Reference. This is a step-by-step guide on how to use feature flags in your Rust applications. +--- + +[![Build Status](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml) +[![crates.io](https://img.shields.io/crates/v/configcat.svg?logo=rust)](https://crates.io/crates/configcat) +[![docs.rs](https://img.shields.io/badge/docs.rs-configcat-66c2a5?logo=docs.rs)](https://docs.rs/configcat) + +ConfigCat Rust SDK on GitHub + +## Getting started + +### 1. Install the package + +Run the following Cargo command in your project directory: +```shell +cargo add configcat +``` + +Or add the following to your `Cargo.toml`: + +```toml +[dependencies] +configcat = "0.1" +``` + +### 2. Import the `configcat` module to your application +```rust +use configcat::*; +``` + +### 3. Create the _ConfigCat_ client with your _SDK Key_ +```rust +use configcat::*; + +#[tokio::main] +async fn main() { + let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +} +``` + +### 4. Get your setting value +```rust +use configcat::*; + +#[tokio::main] +async fn main() { + let client = Client::new("#YOUR-SDK-KEY#").unwrap(); + + let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", None, false).await; + + if is_awesome_feature_enabled { + do_the_new_thing(); + } else { + do_the_old_thing(); + } +} +``` + +## Creating the _ConfigCat Client_ + +_ConfigCat Client_ is responsible for: + +- managing the communication between your application and ConfigCat servers. +- caching your setting values and feature flags. +- serving values quickly in a failsafe way. + +`Client::new()` returns a client with default options. + +| Arguments | Description | +| --------- | ------------------------------------------------------------------------------------------- | +| `sdk_key` | SDK Key to access your feature flags and configurations. Get it from _ConfigCat Dashboard_. | + +### Custom client options + +`Client::builder()` returns a builder used to construct a customized client. + +```rust +use std::time::Duration; +use configcat::{Client, PollingMode, DataGovernance}; + +let builder = Client::builder("#YOUR-SDK-KEY#") + .polling_mode(PollingMode::AutoPoll(Duration::from_secs(60))) + .data_governance(DataGovernance::EU); + +let client = builder.build().unwrap(); +``` + +Available options: + +| Option | Description | +| ----------------------------------- | ------------ | +| `data_governance(DataGovernance)` | Defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | +| `base_url(&str)` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `cache(Box)` | Sets a custom cache implementation for the client. [See below](#cache). | +| `http_timeout(Duration)` | Sets the maximum wait time for a HTTP response. [More about the HTTP timeout](#http-timeout) | +| `polling_mode(PollingMode)` | Defaults to `AutoPoll`. Sets the polling mode for the client. [More about polling modes](#polling-modes). | +| `overrides(Box, OverrideBehavior)` | Sets the local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides). | +| `default_user(User)` | Sets the default user. [More about default user](#default-user). | +| `offline(bool)` | Defaults to `false`. Indicates whether the SDK should be initialized in offline mode. [More about offline mode](#online--offline-mode). | + +:::caution +We strongly recommend you to use the _ConfigCat Client_ as a Singleton object in your application. +If you want to use multiple SDK Keys in the same application, create only one _ConfigCat Client_ per SDK Key. +::: + +## Anatomy of `get_value()` + +| Parameters | Description | +| -------------- | ------------------------------------------------------------------------------------------------------------ | +| `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | +| `default` | **REQUIRED.** This value will be returned in case of an error. | + +```rust +let is_awesome_feature_enabled = client.get_value( + "isAwesomeFeatureEnabled", // Setting Key + Some(User::new("#UNIQUE-USER-IDENTIFIER#")), // Optional User Object + false // Default value +).await; +``` + +:::caution +It is important to provide an argument for the `default` parameter, specifically for the `T` generic type parameter, +that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types. +::: + +### Setting type mapping {#setting-type-mapping} + +| Setting Kind | Type parameter `T` | +| -------------- | ----------------------- | +| On/Off Toggle | `bool` | +| Text | `String` | +| Whole Number | `i64` | +| Decimal Number | `f64` | + +If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `default` will be returned. + +When relying on type inference and not explicitly specifying the type parameter, be mindful of potential type mismatch issues, especially with number types. +For example, `client.get_value("keyOfMyDecimalSetting", None, 0).await` will return `default` (`0`) instead of the actual value of the decimal setting because +the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", None, 0).await`, +which is a type mismatch. + +To correctly evaluate a decimal setting, you should use: + +```rust +let value = client.get_value("keyOfMyDecimalSetting", None, 0.0).await; +// -or- +let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; +``` + +## Anatomy of `get_value_details()` + +`get_value_details()` is similar to `get_value()` but instead of returning the evaluated value only, it provides more detailed information about the evaluation result. + +| Parameters | Description | +| -------------- | ------------------------------------------------------------------------------------------------------------ | +| `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | +| `default` | **REQUIRED.** This value will be returned in case of an error. + +```rust +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); // Optional User Object +let details = client.get_value_details("keyOfMyFeatureFlag", Some(user), false).await; +``` + +:::caution +It is important to provide an argument for the `default` parameter, specifically for the `T` generic type parameter, +that matches the type of the feature flag or setting you are evaluating. Please refer to [this table](#setting-type-mapping) for the corresponding types. +::: + +The `details` result contains the following information: + +| Field | Type | Description | +| --------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------- | +| `key` | `String` | The key of the evaluated feature flag or setting. | +| `value` | `bool` / `String` / `i64` / `f64` | The evaluated value of the feature flag or setting. | +| `user` | `Option` | The User Object used for the evaluation. | +| `is_default_value` | `bool` | True when the default value passed to `GetValueDetailsAsync()` is returned due to an error. | +| `error` | `Option` | In case of an error, this field contains the related error structure. | +| `matched_targeting_rule` | `Option>` | The Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value. | +| `matched_percentage_option` | `Option>` | The Percentage Option (if any) that was used to select the evaluated value. | +| `fetch_time` | `Option>` | The last download time (UTC) of the current config. | + +## User Object + +The [User Object](../targeting/user-object.mdx) is essential if you'd like to use ConfigCat's [Targeting](../targeting/targeting-overview.mdx) feature. + +```rust +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +``` + +```rust +let user = User::new("john@example.com"); +``` + +| Option | Description | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `new()` | **REQUIRED.** Unique identifier of a user in your application. Can be any `string` value, even an email address. | +| `email(&str)` | Optional email address for easier Targeting Rule definitions. | +| `country(&str)` | Optional country for easier Targeting Rule definitions. | +| `custom(&str, Into)` | Optional custom attribute of a user for advanced Targeting Rule definitions. E.g. User role, Subscription type. | + +```rust +let user = new User("#UNIQUE-USER-IDENTIFIER#") + .email("john@example.com") + .country("United Kingdom") + .custom("SubscriptionType", "Pro") + .custom("UserRole", "Admin"); +``` + +The `custom()` method allows attribute values other than `String`: + +```rust +let user = new User("#UNIQUE-USER-IDENTIFIER#") + .custom("Rating", 4.5) + .custom("RegisteredAt", DateTime::from_str("2023-06-14T15:27:15.8440000Z").unwrap()) + .custom("Roles", ["Role1", "Role2"]); +``` + +### User Object Attribute Types + +All comparators support `String` values as User Object attribute (in some cases they need to be provided in a specific format though, see below), +but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply: + +**Text-based comparators** (`EQUALS`, `IS ONE OF`, etc.) +* accept `String` values, +* all other values are automatically converted to `String` (a warning will be logged but evaluation will continue as normal). + +**SemVer-based comparators** (`IS ONE OF`, `<`, `>=`, etc.) +* accept `String` values containing a properly formatted, valid semver value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**Number-based comparators** (`=`, `<`, `>=`, etc.) +* accept `Int`, `UInt`, or `Float` values, +* accept `String` values containing a properly formatted, valid `Float` value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**Date time-based comparators** (`BEFORE` / `AFTER`) +* accept `DateTime` values, which are automatically converted to a second-based Unix timestamp, +* accept `Int`, `UInt`, or `Float` values representing a second-based Unix timestamp, +* accept `String` values containing a properly formatted, valid `Float` value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**String array-based comparators** (`ARRAY CONTAINS ANY OF` / `ARRAY NOT CONTAINS ANY OF`) +* accept `Vec` of `String`s, +* accept `String` values containing a valid JSON string which can be deserialized to an array of `String`, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +### Default user + +It's possible to set a default User Object that will be used on feature flag and setting evaluation. It can be useful when your application has a single user only or rarely switches users. + +You can set the default User Object on SDK initialization: + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .default_user(User::new("john@example.com")) + .build() + .unwrap(); +``` + +Whenever the evaluation methods like `get_value()`, `get_value_details()`, etc. are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + .default_user(User::new("john@example.com")) + .build() + .unwrap(); + +// The default user will be used in the evaluation process. +let value = client.get_value("keyOfMyFeatureFlag", None, false).await; +``` + +When a `user` parameter is passed to the evaluation methods, it takes precedence over the default user. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + .default_user(User::new("john@example.com")) + .build() + .unwrap(); + +let other_user = User::new("brian@example.com"); + +// other_user will be used in the evaluation process. +let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; +``` + +## Polling Modes + +The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. +[More about polling modes.](../advanced/caching.mdx) + +### Auto polling (default) + +The _ConfigCat SDK_ downloads and stores the latest values automatically every 60 seconds. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::AutoPoll(Duration::from_secs(60))) + .build() + .unwrap(); +``` + +### Lazy loading + +When calling `get_value()`, the _ConfigCat SDK_ downloads the latest setting values if they are not present or expired in the cache. In this case `get_value()` will return the setting value after the cache is updated. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::LazyLoad(Duration::from_secs(60))) + .build() + .unwrap(); +``` + +### Manual polling + +Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. _ConfigCat SDK_ will not update them automatically. Calling `refresh()` is your application's responsibility. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::Manual) + .build() + .unwrap(); + +_ = client.refresh().await; +``` + +> `get_value()` returns `default` if the cache is empty. Call `refresh()` to update the cache. + +## Online / Offline mode + +In cases where you want to prevent the SDK from making HTTP calls, you can switch it to offline mode: + +```rust +client.offline(); +``` + +In offline mode, the SDK won't initiate HTTP requests and will work only from its cache. + +To switch the SDK back to online mode, do the following: + +```rust +client.online(); +``` + +Using the `client.is_offline()` method, you can check whether the SDK is in offline mode. + +## Flag Overrides + +With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. +Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported: + +- **Local only** (`OverrideBehavior::LocalOnly`): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources. + +- **Local over remote** (`OverrideBehavior::LocalOverRemote`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence. + +- **Remote over local** (`OverrideBehavior::RemoteOverLocal`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence. + +You can load your feature flag & setting overrides from a file or from a simple `HashMap`. + +### JSON File + +The SDK can load your feature flag & setting overrides from a file. + +#### File + +```rust +use configcat::{Client, FileDataSource, OverrideBehavior}; + +let file_ds = FileDataSource::new("path/to/local_flags.json").unwrap(); + +let client = Client::builder("localhost") + // highlight-next-line + .overrides(Box::new(file_ds), OverrideBehavior::LocalOnly) + .build() + .unwrap(); +``` + +#### JSON File Structure + +The SDK supports 2 types of JSON structures to describe feature flags & settings. + +##### 1. Simple (key-value) structure + +```json +{ + "flags": { + "enabledFeature": true, + "disabledFeature": false, + "intSetting": 5, + "doubleSetting": 3.14, + "stringSetting": "test" + } +} +``` + +##### 2. Complex (full-featured) structure + +This is the same format that the SDK downloads from the ConfigCat CDN. +It allows the usage of all features that are available on the ConfigCat Dashboard. + +You can download your current config JSON from ConfigCat's CDN and use it as a baseline. + +A convenient way to get the config JSON for a specific SDK Key is to install the [ConfigCat CLI](https://github.com/configcat/cli) tool +and execute the following command: + +```bash +configcat config-json get -f v6 -p {YOUR-SDK-KEY} > config.json +``` + +(Depending on your [Data Governance](../advanced/data-governance.mdx) settings, you may need to add the `--eu` switch.) + +Alternatively, you can download the config JSON manually, based on your [Data Governance](../advanced/data-governance.mdx) settings: + +- GLOBAL: `https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json` +- EU: `https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json` + +```json +{ + "p": { + // hash salt, required only when confidential text comparator(s) are used + "s": "80xCU/SlDz1lCiWFaxIBjyJeJecWjq46T4eu6GtozkM=" + }, + "s": [ // array of segments + { + "n": "Beta Users", // segment name + "r": [ // array of User Conditions (there is a logical AND relation between the elements) + { + "a": "Email", // comparison attribute + "c": 0, // comparator (see below) + "l": [ // comparison value (see below) + "john@example.com", "jane@example.com" + ] + } + ] + } + ], + "f": { // key-value map of feature flags & settings + "isFeatureEnabled": { // key of a particular flag / setting + "t": 0, // setting type, possible values: + // 0 -> on/off setting (feature flag) + // 1 -> text setting + // 2 -> whole number setting + // 3 -> decimal number setting + "r": [ // array of Targeting Rules (there is a logical OR relation between the elements) + { + "c": [ // array of conditions (there is a logical AND relation between the elements) + { + "u": { // User Condition + "a": "Email", // comparison attribute + "c": 2, // comparator, possible values and required comparison value types: + // 0 -> IS ONE OF (cleartext) + string array comparison value ("l") + // 1 -> IS NOT ONE OF (cleartext) + string array comparison value ("l") + // 2 -> CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 3 -> NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 4 -> IS ONE OF (semver) + semver string array comparison value ("l") + // 5 -> IS NOT ONE OF (semver) + semver string array comparison value ("l") + // 6 -> < (semver) + semver string comparison value ("s") + // 7 -> <= (semver + semver string comparison value ("s") + // 8 -> > (semver) + semver string comparison value ("s") + // 9 -> >= (semver + semver string comparison value ("s") + // 10 -> = (number) + number comparison value ("d") + // 11 -> <> (number + number comparison value ("d") + // 12 -> < (number) + number comparison value ("d") + // 13 -> <= (number + number comparison value ("d") + // 14 -> > (number) + number comparison value ("d") + // 15 -> >= (number) + number comparison value ("d") + // 16 -> IS ONE OF (hashed) + string array comparison value ("l") + // 17 -> IS NOT ONE OF (hashed) + string array comparison value ("l") + // 18 -> BEFORE (UTC datetime) + second-based Unix timestamp number comparison value ("d") + // 19 -> AFTER (UTC datetime) + second-based Unix timestamp number comparison value ("d") + // 20 -> EQUALS (hashed) + string comparison value ("s") + // 21 -> NOT EQUALS (hashed) + string comparison value ("s") + // 22 -> STARTS WITH ANY OF (hashed) + string array comparison value ("l") + // 23 -> NOT STARTS WITH ANY OF (hashed) + string array comparison value ("l") + // 24 -> ENDS WITH ANY OF (hashed) + string array comparison value ("l") + // 25 -> NOT ENDS WITH ANY OF (hashed) + string array comparison value ("l") + // 26 -> ARRAY CONTAINS ANY OF (hashed) + string array comparison value ("l") + // 27 -> ARRAY NOT CONTAINS ANY OF (hashed) + string array comparison value ("l") + // 28 -> EQUALS (cleartext) + string comparison value ("s") + // 29 -> NOT EQUALS (cleartext) + string comparison value ("s") + // 30 -> STARTS WITH ANY OF (cleartext) + string array comparison value ("l") + // 31 -> NOT STARTS WITH ANY OF (cleartext) + string array comparison value ("l") + // 32 -> ENDS WITH ANY OF (cleartext) + string array comparison value ("l") + // 33 -> NOT ENDS WITH ANY OF (cleartext + string array comparison value ("l") + // 34 -> ARRAY CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 35 -> ARRAY NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l") + "l": [ // comparison value - depending on the comparator, another type of value may need + // to be specified (see above): + // "s": string + // "d": number + "@example.com" + ] + } + }, + { + "p": { // Flag Condition (Prerequisite) + "f": "mainIntFlag", // key of prerequisite flag + "c": 0, // comparator, possible values: 0 -> EQUALS, 1 -> NOT EQUALS + "v": { // comparison value (value's type must match the prerequisite flag's type) + "i": 42 + } + } + }, + { + "s": { // Segment Condition + "s": 0, // segment index, a valid index into the top-level segment array ("s") + "c": 1 // comparator, possible values: 0 -> IS IN SEGMENT, 1 -> IS NOT IN SEGMENT + } + } + ], + "s": { // alternatively, an array of Percentage Options ("p", see below) can also be specified + "v": { // the value served when the rule is selected during evaluation + "b": true + }, + "i": "bcfb84a7" + } + } + ], + "p": [ // array of Percentage Options + { + "p": 10, // % value + "v": { // the value served when the Percentage Option is selected during evaluation + "b": true + }, + "i": "bcfb84a7" + }, + { + "p": 90, + "v": { + "b": false + }, + "i": "bddac6ae" + } + ], + "v": { // fallback value, served when none of the Targeting Rules match, + // no Percentage Options are defined or evaluation of these is not possible + "b": false // depending on the setting type, another type of value may need to be specified: + // text setting -> "s": string + // whole number setting -> "i": number + // decimal number setting -> "d": number + }, + "i": "430bded3" // variation id (for analytical purposes) + } + } +} +``` + +For a more comprehensive specification of the config JSON v6 format, you may refer to [this JSON schema document](https://github.com/configcat/config-json/blob/main/V6/config.schema.json). + +### Map + +You can set up the SDK to load your feature flag & setting overrides from a `HashMap`. + +```rust +use configcat::{Client, MapDataSource, OverrideBehavior, Value}; + +let map: MapDataSource = [ + ("enabledFeature", Value::Bool(true)), + ("disabledFeature", Value::Bool(false)), + ("intSetting", Value::Int(5)), + ("doubleSetting", Value::Float(1.2)), + ("stringSetting", Value::String("test".to_owned())), +].into(); + +let client = Client::builder("localhost") + // highlight-next-line + .overrides(Box::new(map), OverrideBehavior::LocalOnly) + .build() + .unwrap(); +``` + +## `get_all_keys()` + +You can query the keys of each feature flag and setting with the `get_all_keys()` method. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let keys = client.get_all_keys().await; +``` + +## `get_all_values()` + +Evaluates and returns the values of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let values = await client.get_all_values(None).await; + +// invoke with User Object +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +let values_with_user = await client.get_all_values(Some(user)).await; +``` + +## `get_all_details()` + +Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let details = await client.get_all_details(None).await; + +// invoke with User Object +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +let details_with_user = await client.get_all_details(Some(user)).await; +``` + +## Cache + +The _ConfigCat SDK_ stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. +If you prefer to use your own cache solution, such as an external or distributed cache in your system, +you can implement the [`ConfigCache`](https://github.com/configcat/rust-sdk/blob/main/src/cache.rs) trait +and call the `cache()` method of the `ClientBuilder` with your implementation. +This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure. + +```rust +struct CustomCache {} + +impl ConfigCache for CustomCache { + fn read(&self, _: &str) -> Option { + // here you have to return with the cached value + } + + fn write(&self, _: &str, _: &str) { + // here you have to store the new value in the cache + } +} +``` + +Then use your custom cache implementation: + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .cache(Box::new(CustomCache{})) + .build() + .unwrap(); +``` + +## HTTP Proxy + +The SDK uses the [`reqwest`](https://docs.rs/reqwest) crate for HTTP communication. This crate supports [HTTP proxies](https://docs.rs/reqwest/#proxies) via the `HTTP_PROXY` / `HTTPS_PROXY` environment variables. + +## HTTP Timeout + +You can set the maximum wait time for a ConfigCat HTTP response. + +```csharp +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .http_timeout(Duration::from_secs(60)); + .build() + .unwrap(); +``` + +The default timeout is `30` seconds. + +## Logging + +The SDK uses the [`log`](https://docs.rs/log) crate for logging, so you can use any package that implements the `log::Log` trait. + +`Info` level logging helps to inspect how a feature flag was evaluated: + +```bash +INFO [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"","Email":"configcat@example.com","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}' + Evaluating targeting rules and applying the first match if any: + - IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match + - IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule + Returning 'true'. +``` + +## Sample Applications + +Check out our Sample Applications how they use the _ConfigCat SDK_: + +- Sample App + +## Look under the hood + +- ConfigCat Rust SDK on GitHub +- ConfigCat Rust SDK on crates.io +- ConfigCat Rust SDK on docs.rs \ No newline at end of file diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts index eda653d4..608ff226 100644 --- a/website/docusaurus.config.ts +++ b/website/docusaurus.config.ts @@ -294,7 +294,8 @@ const config: Config = { 'objectivec', 'protobuf', 'json', - 'bash' + 'bash', + 'rust', ], }, algolia: { diff --git a/website/sidebars.ts b/website/sidebars.ts index 91787225..2c188c51 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -216,6 +216,7 @@ const sidebars: SidebarsConfig = { { type: 'doc', id: 'sdk-reference/php', label: 'PHP' }, { type: 'doc', id: 'sdk-reference/python', label: 'Python' }, { type: 'doc', id: 'sdk-reference/ruby', label: 'Ruby' }, + { type: 'doc', id: 'sdk-reference/rust', label: 'Rust' }, { type: 'doc', id: 'sdk-reference/ios', label: 'Swift (iOS)' }, { 'Community Maintained': [ diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 01781c9a..78429c95 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -77,6 +77,7 @@ const features = [ { url: 'sdk-reference/community/laravel', title: 'PHP (Laravel)' }, { url: 'sdk-reference/python', title: 'Python' }, { url: 'sdk-reference/ruby', title: 'Ruby' }, + { url: 'sdk-reference/rust', title: 'Rust' }, { url: 'sdk-reference/ios', title: 'Swift (iOS)' }, ], }, diff --git a/website/versioned_docs/version-V1/sdk-reference/android.mdx b/website/versioned_docs/version-V1/sdk-reference/android.mdx index baf77e52..9fc276b8 100644 --- a/website/versioned_docs/version-V1/sdk-reference/android.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/android.mdx @@ -115,7 +115,7 @@ These are the available options on the `Options` class: | Options | Description | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataGovernance(DataGovernance)` | Optional, defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `baseUrl(string)` | _Obsolete_ Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | +| `baseUrl(string)` | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | | `httpClient(OkHttpClient)` | Optional, sets the underlying `OkHttpClient` used to download the feature flags and settings over HTTP. [More about the HTTP Client](#httpclient). | | `cache(ConfigCache)` | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache). | | `pollingMode(PollingMode)` | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes). | diff --git a/website/versioned_docs/version-V1/sdk-reference/go.mdx b/website/versioned_docs/version-V1/sdk-reference/go.mdx index c3b36fd6..33115e8b 100644 --- a/website/versioned_docs/version-V1/sdk-reference/go.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/go.mdx @@ -88,7 +88,7 @@ Available optional properties: | ------------------ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SDKKey` | `string` | SDK Key to access your feature flags and configurations. Get it from _ConfigCat Dashboard_. | | `DataGovernance` | `configcat.DataGovernance` | Defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `BaseUrl` | `string` | _Obsolete_ Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `BaseUrl` | `string` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | | `Cache ` | `ConfigCache` | Sets a custom cache implementation for the client. [See below](#custom-cache). | | `NoWaitForRefresh` | `bool` | Defaults to `false`. When it's `true` the typed get methods (`Get[TYPE]Value()`) will never wait for a configuration refresh to complete before returning. When it's `false` and `PollingMode` is `AutoPoll`, the first request may block, when `PollingMode` is `Lazy`, any request may block. | | `HttpTimeout` | `time.Duration` | Sets the maximum wait time for a HTTP response. [More about the HTTP timeout](#http-timeout) | diff --git a/website/versioned_docs/version-V1/sdk-reference/java.mdx b/website/versioned_docs/version-V1/sdk-reference/java.mdx index a42b64a2..b2395303 100644 --- a/website/versioned_docs/version-V1/sdk-reference/java.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/java.mdx @@ -120,7 +120,7 @@ These are the available options on the `Options` class: | Option | Description | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataGovernance(DataGovernance)` | Optional, defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | -| `baseUrl(string)` | _Obsolete_ Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `baseUrl(string)` | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | | `httpClient(OkHttpClient)` | Optional, sets the underlying `OkHttpClient` used to download the feature flags and settings over HTTP. [More about the HTTP Client](#httpclient). | | `cache(ConfigCache)` | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache). | | `pollingMode(PollingMode)` | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes). | diff --git a/website/versioned_docs/version-V1/sdk-reference/ruby.mdx b/website/versioned_docs/version-V1/sdk-reference/ruby.mdx index 6686e83d..19ecdaaf 100644 --- a/website/versioned_docs/version-V1/sdk-reference/ruby.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/ruby.mdx @@ -74,7 +74,7 @@ _ConfigCat Client_ is responsible for: | Client options | Description | Default | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| `base_url` | _Obsolete_, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | nil | +| `base_url` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | nil | | `polling_mode` | Sets the polling mode for the client. [More about polling modes](#polling-modes). | PollingMode.auto_poll | | `config_cache` | Sets a custom config cache implementation for the client. [More about cache](#custom-cache). | nil | | `proxy_address` | Sets custom proxy address for the client. [More about proxy](#using-configcat-behind-a-proxy). | nil | diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx new file mode 100644 index 00000000..5d247a57 --- /dev/null +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -0,0 +1,689 @@ +--- +id: rust +title: Rust SDK Reference +description: ConfigCat Rust SDK Reference. This is a step-by-step guide on how to use feature flags in your Rust applications. +--- + +[![Build Status](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml) +[![crates.io](https://img.shields.io/crates/v/configcat.svg?logo=rust)](https://crates.io/crates/configcat) +[![docs.rs](https://img.shields.io/badge/docs.rs-configcat-66c2a5?logo=docs.rs)](https://docs.rs/configcat) + +ConfigCat Rust SDK on GitHub + +## Getting started + +### 1. Install the package + +Run the following Cargo command in your project directory: +```shell +cargo add configcat +``` + +Or add the following to your `Cargo.toml`: + +```toml +[dependencies] +configcat = "0.1" +``` + +### 2. Import the `configcat` module to your application +```rust +use configcat::*; +``` + +### 3. Create the _ConfigCat_ client with your _SDK Key_ +```rust +use configcat::*; + +#[tokio::main] +async fn main() { + let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +} +``` + +### 4. Get your setting value +```rust +use configcat::*; + +#[tokio::main] +async fn main() { + let client = Client::new("#YOUR-SDK-KEY#").unwrap(); + + let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", None, false).await; + + if is_awesome_feature_enabled { + do_the_new_thing(); + } else { + do_the_old_thing(); + } +} +``` + +## Creating the _ConfigCat Client_ + +_ConfigCat Client_ is responsible for: + +- managing the communication between your application and ConfigCat servers. +- caching your setting values and feature flags. +- serving values quickly in a failsafe way. + +`Client::new()` returns a client with default options. + +| Arguments | Description | +| --------- | ------------------------------------------------------------------------------------------- | +| `sdk_key` | SDK Key to access your feature flags and configurations. Get it from _ConfigCat Dashboard_. | + +### Custom client options + +`Client::builder()` returns a builder used to construct a customized client. + +```rust +use std::time::Duration; +use configcat::{Client, PollingMode, DataGovernance}; + +let builder = Client::builder("#YOUR-SDK-KEY#") + .polling_mode(PollingMode::AutoPoll(Duration::from_secs(60))) + .data_governance(DataGovernance::EU); + +let client = builder.build().unwrap(); +``` + +Available options: + +| Option | Description | +| ----------------------------------- | ------------ | +| `data_governance(DataGovernance)` | Defaults to `Global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](../advanced/data-governance.mdx). Available options: `Global`, `EuOnly`. | +| `base_url(&str)` | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. | +| `cache(Box)` | Sets a custom cache implementation for the client. [See below](#cache). | +| `http_timeout(Duration)` | Sets the maximum wait time for a HTTP response. [More about the HTTP timeout](#http-timeout) | +| `polling_mode(PollingMode)` | Defaults to `AutoPoll`. Sets the polling mode for the client. [More about polling modes](#polling-modes). | +| `overrides(Box, OverrideBehavior)` | Sets the local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides). | +| `default_user(User)` | Sets the default user. [More about default user](#default-user). | +| `offline(bool)` | Defaults to `false`. Indicates whether the SDK should be initialized in offline mode. [More about offline mode](#online--offline-mode). | + +:::caution +We strongly recommend you to use the _ConfigCat Client_ as a Singleton object in your application. +If you want to use multiple SDK Keys in the same application, create only one _ConfigCat Client_ per SDK Key. +::: + +## Anatomy of `get_value()` + +| Parameters | Description | +| -------------- | ------------------------------------------------------------------------------------------------------------ | +| `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | +| `default` | **REQUIRED.** This value will be returned in case of an error. | + +```rust +let is_awesome_feature_enabled = client.get_value( + "isAwesomeFeatureEnabled", // Setting Key + Some(User::new("#UNIQUE-USER-IDENTIFIER#")), // Optional User Object + false // Default value +).await; +``` + +:::caution +It is important to provide an argument for the `default` parameter, specifically for the `T` generic type parameter, +that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types. +::: + +### Setting type mapping {#setting-type-mapping} + +| Setting Kind | Type parameter `T` | +| -------------- | ----------------------- | +| On/Off Toggle | `bool` | +| Text | `String` | +| Whole Number | `i64` | +| Decimal Number | `f64` | + +If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `default` will be returned. + +When relying on type inference and not explicitly specifying the type parameter, be mindful of potential type mismatch issues, especially with number types. +For example, `client.get_value("keyOfMyDecimalSetting", None, 0).await` will return `default` (`0`) instead of the actual value of the decimal setting because +the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", None, 0).await`, +which is a type mismatch. + +To correctly evaluate a decimal setting, you should use: + +```rust +let value = client.get_value("keyOfMyDecimalSetting", None, 0.0).await; +// -or- +let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; +``` + +## Anatomy of `get_value_details()` + +`get_value_details()` is similar to `get_value()` but instead of returning the evaluated value only, it provides more detailed information about the evaluation result. + +| Parameters | Description | +| -------------- | ------------------------------------------------------------------------------------------------------------ | +| `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | +| `default` | **REQUIRED.** This value will be returned in case of an error. + +```rust +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); // Optional User Object +let details = client.get_value_details("keyOfMyFeatureFlag", Some(user), false).await; +``` + +:::caution +It is important to provide an argument for the `default` parameter, specifically for the `T` generic type parameter, +that matches the type of the feature flag or setting you are evaluating. Please refer to [this table](#setting-type-mapping) for the corresponding types. +::: + +The `details` result contains the following information: + +| Field | Type | Description | +| --------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------- | +| `key` | `String` | The key of the evaluated feature flag or setting. | +| `value` | `bool` / `String` / `i64` / `f64` | The evaluated value of the feature flag or setting. | +| `user` | `Option` | The User Object used for the evaluation. | +| `is_default_value` | `bool` | True when the default value passed to `GetValueDetailsAsync()` is returned due to an error. | +| `error` | `Option` | In case of an error, this field contains the related error structure. | +| `matched_targeting_rule` | `Option>` | The Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value. | +| `matched_percentage_option` | `Option>` | The Percentage Option (if any) that was used to select the evaluated value. | +| `fetch_time` | `Option>` | The last download time (UTC) of the current config. | + +## User Object + +The [User Object](../advanced/user-object.mdx) is essential if you'd like to use ConfigCat's [Targeting](../advanced/targeting.mdx) feature. + +```rust +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +``` + +```rust +let user = User::new("john@example.com"); +``` + +| Option | Description | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `new()` | **REQUIRED.** Unique identifier of a user in your application. Can be any `string` value, even an email address. | +| `email(&str)` | Optional email address for easier Targeting Rule definitions. | +| `country(&str)` | Optional country for easier Targeting Rule definitions. | +| `custom(&str, Into)` | Optional custom attribute of a user for advanced Targeting Rule definitions. E.g. User role, Subscription type. | + +```rust +let user = new User("#UNIQUE-USER-IDENTIFIER#") + .email("john@example.com") + .country("United Kingdom") + .custom("SubscriptionType", "Pro") + .custom("UserRole", "Admin"); +``` + +The `custom()` method allows attribute values other than `String`: + +```rust +let user = new User("#UNIQUE-USER-IDENTIFIER#") + .custom("Rating", 4.5) + .custom("RegisteredAt", DateTime::from_str("2023-06-14T15:27:15.8440000Z").unwrap()) + .custom("Roles", ["Role1", "Role2"]); +``` + +### User Object Attribute Types + +All comparators support `String` values as User Object attribute (in some cases they need to be provided in a specific format though, see below), +but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply: + +**Text-based comparators** (`EQUALS`, `IS ONE OF`, etc.) +* accept `String` values, +* all other values are automatically converted to `String` (a warning will be logged but evaluation will continue as normal). + +**SemVer-based comparators** (`IS ONE OF`, `<`, `>=`, etc.) +* accept `String` values containing a properly formatted, valid semver value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**Number-based comparators** (`=`, `<`, `>=`, etc.) +* accept `Int`, `UInt`, or `Float` values, +* accept `String` values containing a properly formatted, valid `Float` value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**Date time-based comparators** (`BEFORE` / `AFTER`) +* accept `DateTime` values, which are automatically converted to a second-based Unix timestamp, +* accept `Int`, `UInt`, or `Float` values representing a second-based Unix timestamp, +* accept `String` values containing a properly formatted, valid `Float` value, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +**String array-based comparators** (`ARRAY CONTAINS ANY OF` / `ARRAY NOT CONTAINS ANY OF`) +* accept `Vec` of `String`s, +* accept `String` values containing a valid JSON string which can be deserialized to an array of `String`, +* all other values are considered invalid (a warning will be logged and the currently evaluated targeting rule will be skipped). + +### Default user + +It's possible to set a default User Object that will be used on feature flag and setting evaluation. It can be useful when your application has a single user only or rarely switches users. + +You can set the default User Object on SDK initialization: + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .default_user(User::new("john@example.com")) + .build() + .unwrap(); +``` + +Whenever the evaluation methods like `get_value()`, `get_value_details()`, etc. are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + .default_user(User::new("john@example.com")) + .build() + .unwrap(); + +// The default user will be used in the evaluation process. +let value = client.get_value("keyOfMyFeatureFlag", None, false).await; +``` + +When a `user` parameter is passed to the evaluation methods, it takes precedence over the default user. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + .default_user(User::new("john@example.com")) + .build() + .unwrap(); + +let other_user = User::new("brian@example.com"); + +// other_user will be used in the evaluation process. +let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; +``` + +## Polling Modes + +The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. +[More about polling modes.](../advanced/caching.mdx) + +### Auto polling (default) + +The _ConfigCat SDK_ downloads and stores the latest values automatically every 60 seconds. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::AutoPoll(Duration::from_secs(60))) + .build() + .unwrap(); +``` + +### Lazy loading + +When calling `get_value()`, the _ConfigCat SDK_ downloads the latest setting values if they are not present or expired in the cache. In this case `get_value()` will return the setting value after the cache is updated. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::LazyLoad(Duration::from_secs(60))) + .build() + .unwrap(); +``` + +### Manual polling + +Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. _ConfigCat SDK_ will not update them automatically. Calling `refresh()` is your application's responsibility. + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .polling_mode(PollingMode::Manual) + .build() + .unwrap(); + +_ = client.refresh().await; +``` + +> `get_value()` returns `default` if the cache is empty. Call `refresh()` to update the cache. + +## Online / Offline mode + +In cases where you want to prevent the SDK from making HTTP calls, you can switch it to offline mode: + +```rust +client.offline(); +``` + +In offline mode, the SDK won't initiate HTTP requests and will work only from its cache. + +To switch the SDK back to online mode, do the following: + +```rust +client.online(); +``` + +Using the `client.is_offline()` method, you can check whether the SDK is in offline mode. + +## Flag Overrides + +With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. +Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported: + +- **Local only** (`OverrideBehavior::LocalOnly`): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources. + +- **Local over remote** (`OverrideBehavior::LocalOverRemote`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence. + +- **Remote over local** (`OverrideBehavior::RemoteOverLocal`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence. + +You can load your feature flag & setting overrides from a file or from a simple `HashMap`. + +### JSON File + +The SDK can load your feature flag & setting overrides from a file. + +#### File + +```rust +use configcat::{Client, FileDataSource, OverrideBehavior}; + +let file_ds = FileDataSource::new("path/to/local_flags.json").unwrap(); + +let client = Client::builder("localhost") + // highlight-next-line + .overrides(Box::new(file_ds), OverrideBehavior::LocalOnly) + .build() + .unwrap(); +``` + +#### JSON File Structure + +The SDK supports 2 types of JSON structures to describe feature flags & settings. + +##### 1. Simple (key-value) structure + +```json +{ + "flags": { + "enabledFeature": true, + "disabledFeature": false, + "intSetting": 5, + "doubleSetting": 3.14, + "stringSetting": "test" + } +} +``` + +##### 2. Complex (full-featured) structure + +This is the same format that the SDK downloads from the ConfigCat CDN. +It allows the usage of all features that are available on the ConfigCat Dashboard. + +You can download your current config JSON from ConfigCat's CDN and use it as a baseline. + +A convenient way to get the config JSON for a specific SDK Key is to install the [ConfigCat CLI](https://github.com/configcat/cli) tool +and execute the following command: + +```bash +configcat config-json get -f v6 -p {YOUR-SDK-KEY} > config.json +``` + +(Depending on your [Data Governance](../advanced/data-governance.mdx) settings, you may need to add the `--eu` switch.) + +Alternatively, you can download the config JSON manually, based on your [Data Governance](../advanced/data-governance.mdx) settings: + +- GLOBAL: `https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json` +- EU: `https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json` + +```json +{ + "p": { + // hash salt, required only when confidential text comparator(s) are used + "s": "80xCU/SlDz1lCiWFaxIBjyJeJecWjq46T4eu6GtozkM=" + }, + "s": [ // array of segments + { + "n": "Beta Users", // segment name + "r": [ // array of User Conditions (there is a logical AND relation between the elements) + { + "a": "Email", // comparison attribute + "c": 0, // comparator (see below) + "l": [ // comparison value (see below) + "john@example.com", "jane@example.com" + ] + } + ] + } + ], + "f": { // key-value map of feature flags & settings + "isFeatureEnabled": { // key of a particular flag / setting + "t": 0, // setting type, possible values: + // 0 -> on/off setting (feature flag) + // 1 -> text setting + // 2 -> whole number setting + // 3 -> decimal number setting + "r": [ // array of Targeting Rules (there is a logical OR relation between the elements) + { + "c": [ // array of conditions (there is a logical AND relation between the elements) + { + "u": { // User Condition + "a": "Email", // comparison attribute + "c": 2, // comparator, possible values and required comparison value types: + // 0 -> IS ONE OF (cleartext) + string array comparison value ("l") + // 1 -> IS NOT ONE OF (cleartext) + string array comparison value ("l") + // 2 -> CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 3 -> NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 4 -> IS ONE OF (semver) + semver string array comparison value ("l") + // 5 -> IS NOT ONE OF (semver) + semver string array comparison value ("l") + // 6 -> < (semver) + semver string comparison value ("s") + // 7 -> <= (semver + semver string comparison value ("s") + // 8 -> > (semver) + semver string comparison value ("s") + // 9 -> >= (semver + semver string comparison value ("s") + // 10 -> = (number) + number comparison value ("d") + // 11 -> <> (number + number comparison value ("d") + // 12 -> < (number) + number comparison value ("d") + // 13 -> <= (number + number comparison value ("d") + // 14 -> > (number) + number comparison value ("d") + // 15 -> >= (number) + number comparison value ("d") + // 16 -> IS ONE OF (hashed) + string array comparison value ("l") + // 17 -> IS NOT ONE OF (hashed) + string array comparison value ("l") + // 18 -> BEFORE (UTC datetime) + second-based Unix timestamp number comparison value ("d") + // 19 -> AFTER (UTC datetime) + second-based Unix timestamp number comparison value ("d") + // 20 -> EQUALS (hashed) + string comparison value ("s") + // 21 -> NOT EQUALS (hashed) + string comparison value ("s") + // 22 -> STARTS WITH ANY OF (hashed) + string array comparison value ("l") + // 23 -> NOT STARTS WITH ANY OF (hashed) + string array comparison value ("l") + // 24 -> ENDS WITH ANY OF (hashed) + string array comparison value ("l") + // 25 -> NOT ENDS WITH ANY OF (hashed) + string array comparison value ("l") + // 26 -> ARRAY CONTAINS ANY OF (hashed) + string array comparison value ("l") + // 27 -> ARRAY NOT CONTAINS ANY OF (hashed) + string array comparison value ("l") + // 28 -> EQUALS (cleartext) + string comparison value ("s") + // 29 -> NOT EQUALS (cleartext) + string comparison value ("s") + // 30 -> STARTS WITH ANY OF (cleartext) + string array comparison value ("l") + // 31 -> NOT STARTS WITH ANY OF (cleartext) + string array comparison value ("l") + // 32 -> ENDS WITH ANY OF (cleartext) + string array comparison value ("l") + // 33 -> NOT ENDS WITH ANY OF (cleartext + string array comparison value ("l") + // 34 -> ARRAY CONTAINS ANY OF (cleartext) + string array comparison value ("l") + // 35 -> ARRAY NOT CONTAINS ANY OF (cleartext) + string array comparison value ("l") + "l": [ // comparison value - depending on the comparator, another type of value may need + // to be specified (see above): + // "s": string + // "d": number + "@example.com" + ] + } + }, + { + "p": { // Flag Condition (Prerequisite) + "f": "mainIntFlag", // key of prerequisite flag + "c": 0, // comparator, possible values: 0 -> EQUALS, 1 -> NOT EQUALS + "v": { // comparison value (value's type must match the prerequisite flag's type) + "i": 42 + } + } + }, + { + "s": { // Segment Condition + "s": 0, // segment index, a valid index into the top-level segment array ("s") + "c": 1 // comparator, possible values: 0 -> IS IN SEGMENT, 1 -> IS NOT IN SEGMENT + } + } + ], + "s": { // alternatively, an array of Percentage Options ("p", see below) can also be specified + "v": { // the value served when the rule is selected during evaluation + "b": true + }, + "i": "bcfb84a7" + } + } + ], + "p": [ // array of Percentage Options + { + "p": 10, // % value + "v": { // the value served when the Percentage Option is selected during evaluation + "b": true + }, + "i": "bcfb84a7" + }, + { + "p": 90, + "v": { + "b": false + }, + "i": "bddac6ae" + } + ], + "v": { // fallback value, served when none of the Targeting Rules match, + // no Percentage Options are defined or evaluation of these is not possible + "b": false // depending on the setting type, another type of value may need to be specified: + // text setting -> "s": string + // whole number setting -> "i": number + // decimal number setting -> "d": number + }, + "i": "430bded3" // variation id (for analytical purposes) + } + } +} +``` + +For a more comprehensive specification of the config JSON v6 format, you may refer to [this JSON schema document](https://github.com/configcat/config-json/blob/main/V6/config.schema.json). + +### Map + +You can set up the SDK to load your feature flag & setting overrides from a `HashMap`. + +```rust +use configcat::{Client, MapDataSource, OverrideBehavior, Value}; + +let map: MapDataSource = [ + ("enabledFeature", Value::Bool(true)), + ("disabledFeature", Value::Bool(false)), + ("intSetting", Value::Int(5)), + ("doubleSetting", Value::Float(1.2)), + ("stringSetting", Value::String("test".to_owned())), +].into(); + +let client = Client::builder("localhost") + // highlight-next-line + .overrides(Box::new(map), OverrideBehavior::LocalOnly) + .build() + .unwrap(); +``` + +## `get_all_keys()` + +You can query the keys of each feature flag and setting with the `get_all_keys()` method. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let keys = client.get_all_keys().await; +``` + +## `get_all_values()` + +Evaluates and returns the values of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let values = await client.get_all_values(None).await; + +// invoke with User Object +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +let values_with_user = await client.get_all_values(Some(user)).await; +``` + +## `get_all_details()` + +Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a [User Object](#user-object) is optional. + +```rust +let client = Client::new("#YOUR-SDK-KEY#").unwrap(); +let details = await client.get_all_details(None).await; + +// invoke with User Object +let user = User::new("#UNIQUE-USER-IDENTIFIER#"); +let details_with_user = await client.get_all_details(Some(user)).await; +``` + +## Cache + +The _ConfigCat SDK_ stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. +If you prefer to use your own cache solution, such as an external or distributed cache in your system, +you can implement the [`ConfigCache`](https://github.com/configcat/rust-sdk/blob/main/src/cache.rs) trait +and call the `cache()` method of the `ClientBuilder` with your implementation. +This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure. + +```rust +struct CustomCache {} + +impl ConfigCache for CustomCache { + fn read(&self, _: &str) -> Option { + // here you have to return with the cached value + } + + fn write(&self, _: &str, _: &str) { + // here you have to store the new value in the cache + } +} +``` + +Then use your custom cache implementation: + +```rust +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .cache(Box::new(CustomCache{})) + .build() + .unwrap(); +``` + +## HTTP Proxy + +The SDK uses the [`reqwest`](https://docs.rs/reqwest) crate for HTTP communication. This crate supports [HTTP proxies](https://docs.rs/reqwest/#proxies) via the `HTTP_PROXY` / `HTTPS_PROXY` environment variables. + +## HTTP Timeout + +You can set the maximum wait time for a ConfigCat HTTP response. + +```csharp +let client = Client::builder("#YOUR-SDK-KEY#") + // highlight-next-line + .http_timeout(Duration::from_secs(60)); + .build() + .unwrap(); +``` + +The default timeout is `30` seconds. + +## Logging + +The SDK uses the [`log`](https://docs.rs/log) crate for logging, so you can use any package that implements the `log::Log` trait. + +`Info` level logging helps to inspect how a feature flag was evaluated: + +```bash +INFO [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"","Email":"configcat@example.com","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}' + Evaluating targeting rules and applying the first match if any: + - IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match + - IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule + Returning 'true'. +``` + +## Sample Applications + +Check out our Sample Applications how they use the _ConfigCat SDK_: + +- Sample App + +## Look under the hood + +- ConfigCat Rust SDK on GitHub +- ConfigCat Rust SDK on crates.io +- ConfigCat Rust SDK on docs.rs \ No newline at end of file diff --git a/website/versioned_sidebars/version-V1-sidebars.json b/website/versioned_sidebars/version-V1-sidebars.json index 5b31555a..0ac857f4 100644 --- a/website/versioned_sidebars/version-V1-sidebars.json +++ b/website/versioned_sidebars/version-V1-sidebars.json @@ -350,6 +350,11 @@ "id": "sdk-reference/ruby", "label": "Ruby" }, + { + "type": "doc", + "id": "sdk-reference/rust", + "label": "Rust" + }, { "type": "doc", "id": "sdk-reference/ios", From 4844321613f94c13eadb048f270ced1565e5679a Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Tue, 11 Jun 2024 20:29:45 +0200 Subject: [PATCH 2/8] Fixup --- website/docs/sdk-reference/rust.mdx | 4 ++-- website/versioned_docs/version-V1/sdk-reference/rust.mdx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index fe52ae72..747c7bc9 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -624,11 +624,11 @@ This allows you to seamlessly integrate ConfigCat with your existing caching inf struct CustomCache {} impl ConfigCache for CustomCache { - fn read(&self, _: &str) -> Option { + fn read(&self, key: &str) -> Option { // here you have to return with the cached value } - fn write(&self, _: &str, _: &str) { + fn write(&self, key: &str, value: &str) { // here you have to store the new value in the cache } } diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index 5d247a57..13cddb69 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -624,11 +624,11 @@ This allows you to seamlessly integrate ConfigCat with your existing caching inf struct CustomCache {} impl ConfigCache for CustomCache { - fn read(&self, _: &str) -> Option { + fn read(&self, key: &str) -> Option { // here you have to return with the cached value } - fn write(&self, _: &str, _: &str) { + fn write(&self, key: &str, value: &str) { // here you have to store the new value in the cache } } From bd1c9b608b7d229110fdd1e0f2d528d2df68a6a7 Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Wed, 12 Jun 2024 11:54:22 +0200 Subject: [PATCH 3/8] Apply PR suggestions --- website/docs/sdk-reference/rust.mdx | 20 +++++++++++++++++-- website/docusaurus.config.ts | 1 + .../version-V1/sdk-reference/rust.mdx | 20 ++++++++++++++++--- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index 747c7bc9..f7bcbd4d 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -253,7 +253,7 @@ but some of them also support other types of values. It depends on the comparato It's possible to set a default User Object that will be used on feature flag and setting evaluation. It can be useful when your application has a single user only or rarely switches users. -You can set the default User Object on SDK initialization: +You can set the default User Object either on SDK initialization: ```rust let client = Client::builder("#YOUR-SDK-KEY#") @@ -263,6 +263,12 @@ let client = Client::builder("#YOUR-SDK-KEY#") .unwrap(); ``` +...or using the `set_default_user()` method of the `configcat::Client`: + +```csharp +client.set_default_user(User::new("john@example.com")); +``` + Whenever the evaluation methods like `get_value()`, `get_value_details()`, etc. are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object. ```rust @@ -289,14 +295,23 @@ let other_user = User::new("brian@example.com"); let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; ``` +You can also remove the default user by doing the following: + +```csharp +client.clear_default_user(); +``` + ## Polling Modes The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. + +When no polling mode is specified upon SDK initialization, `AutoPoll` will be selected with a `60s` poll interval. + [More about polling modes.](../advanced/caching.mdx) ### Auto polling (default) -The _ConfigCat SDK_ downloads and stores the latest values automatically every 60 seconds. +The _ConfigCat SDK_ downloads and stores the latest values automatically. The `Duration` parameter specifies how frequent the config JSON downloads will happen. ```rust let client = Client::builder("#YOUR-SDK-KEY#") @@ -309,6 +324,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") ### Lazy loading When calling `get_value()`, the _ConfigCat SDK_ downloads the latest setting values if they are not present or expired in the cache. In this case `get_value()` will return the setting value after the cache is updated. +The `Duration` parameter specifies after how much time the cache is considered stale. ```rust let client = Client::builder("#YOUR-SDK-KEY#") diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts index 608ff226..3f632c4b 100644 --- a/website/docusaurus.config.ts +++ b/website/docusaurus.config.ts @@ -296,6 +296,7 @@ const config: Config = { 'json', 'bash', 'rust', + 'toml', ], }, algolia: { diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index 13cddb69..24b4caf6 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -253,7 +253,7 @@ but some of them also support other types of values. It depends on the comparato It's possible to set a default User Object that will be used on feature flag and setting evaluation. It can be useful when your application has a single user only or rarely switches users. -You can set the default User Object on SDK initialization: +You can set the default User Object either on SDK initialization: ```rust let client = Client::builder("#YOUR-SDK-KEY#") @@ -263,6 +263,12 @@ let client = Client::builder("#YOUR-SDK-KEY#") .unwrap(); ``` +...or using the `set_default_user()` method of the `configcat::Client`: + +```csharp +client.set_default_user(User::new("john@example.com")); +``` + Whenever the evaluation methods like `get_value()`, `get_value_details()`, etc. are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object. ```rust @@ -289,14 +295,21 @@ let other_user = User::new("brian@example.com"); let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; ``` -## Polling Modes +You can also remove the default user by doing the following: + +```csharp +client.clear_default_user(); +``` The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. + +When no polling mode is specified upon SDK initialization, `AutoPoll` will be selected with a `60s` poll interval. + [More about polling modes.](../advanced/caching.mdx) ### Auto polling (default) -The _ConfigCat SDK_ downloads and stores the latest values automatically every 60 seconds. +The _ConfigCat SDK_ downloads and stores the latest values automatically. The `Duration` parameter specifies how frequent the config JSON downloads will happen. ```rust let client = Client::builder("#YOUR-SDK-KEY#") @@ -309,6 +322,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") ### Lazy loading When calling `get_value()`, the _ConfigCat SDK_ downloads the latest setting values if they are not present or expired in the cache. In this case `get_value()` will return the setting value after the cache is updated. +The `Duration` parameter specifies after how much time the cache is considered stale. ```rust let client = Client::builder("#YOUR-SDK-KEY#") From 4042e5b4021f21b19e03af7674f6bcc3745bd894 Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Wed, 12 Jun 2024 11:59:11 +0200 Subject: [PATCH 4/8] Update rust.mdx --- website/versioned_docs/version-V1/sdk-reference/rust.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index 24b4caf6..3d776026 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -301,6 +301,8 @@ You can also remove the default user by doing the following: client.clear_default_user(); ``` +## Polling Modes + The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. When no polling mode is specified upon SDK initialization, `AutoPoll` will be selected with a `60s` poll interval. From bc6e1357b0caf8bf453c265f35f382d11f09c5be Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Wed, 12 Jun 2024 12:57:52 +0200 Subject: [PATCH 5/8] Fixup get_value() parameter order --- website/docs/sdk-reference/rust.mdx | 24 +++++++++---------- .../version-V1/sdk-reference/rust.mdx | 24 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index f7bcbd4d..366f8e99 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -49,7 +49,7 @@ use configcat::*; async fn main() { let client = Client::new("#YOUR-SDK-KEY#").unwrap(); - let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", None, false).await; + let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", false, None).await; if is_awesome_feature_enabled { do_the_new_thing(); @@ -111,14 +111,14 @@ If you want to use multiple SDK Keys in the same application, create only one _C | Parameters | Description | | -------------- | ------------------------------------------------------------------------------------------------------------ | | `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | -| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | | `default` | **REQUIRED.** This value will be returned in case of an error. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | ```rust let is_awesome_feature_enabled = client.get_value( "isAwesomeFeatureEnabled", // Setting Key - Some(User::new("#UNIQUE-USER-IDENTIFIER#")), // Optional User Object - false // Default value + false, // Default value + Some(User::new("#UNIQUE-USER-IDENTIFIER#")) // Optional User Object ).await; ``` @@ -139,16 +139,16 @@ that matches the type of the feature flag or setting you are evaluating. Please If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `default` will be returned. When relying on type inference and not explicitly specifying the type parameter, be mindful of potential type mismatch issues, especially with number types. -For example, `client.get_value("keyOfMyDecimalSetting", None, 0).await` will return `default` (`0`) instead of the actual value of the decimal setting because -the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", None, 0).await`, +For example, `client.get_value("keyOfMyDecimalSetting", 0, None).await` will return `default` (`0`) instead of the actual value of the decimal setting because +the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", 0, None).await`, which is a type mismatch. To correctly evaluate a decimal setting, you should use: ```rust -let value = client.get_value("keyOfMyDecimalSetting", None, 0.0).await; +let value = client.get_value("keyOfMyDecimalSetting", 0.0, None).await; // -or- -let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; +let value = client.get_value("keyOfMyDecimalSetting", 0_f64, None).await; ``` ## Anatomy of `get_value_details()` @@ -158,12 +158,12 @@ let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; | Parameters | Description | | -------------- | ------------------------------------------------------------------------------------------------------------ | | `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | -| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | | `default` | **REQUIRED.** This value will be returned in case of an error. +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../targeting/targeting-overview.mdx) | ```rust let user = User::new("#UNIQUE-USER-IDENTIFIER#"); // Optional User Object -let details = client.get_value_details("keyOfMyFeatureFlag", Some(user), false).await; +let details = client.get_value_details("keyOfMyFeatureFlag", false, Some(user)).await; ``` :::caution @@ -278,7 +278,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") .unwrap(); // The default user will be used in the evaluation process. -let value = client.get_value("keyOfMyFeatureFlag", None, false).await; +let value = client.get_value("keyOfMyFeatureFlag", false, None).await; ``` When a `user` parameter is passed to the evaluation methods, it takes precedence over the default user. @@ -292,7 +292,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") let other_user = User::new("brian@example.com"); // other_user will be used in the evaluation process. -let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; +let value = client.get_value("keyOfMyFeatureFlag", false, Some(other_user)).await; ``` You can also remove the default user by doing the following: diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index 3d776026..3b84b02e 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -49,7 +49,7 @@ use configcat::*; async fn main() { let client = Client::new("#YOUR-SDK-KEY#").unwrap(); - let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", None, false).await; + let is_awesome_feature_enabled = client.get_value("isAwesomeFeatureEnabled", false, None).await; if is_awesome_feature_enabled { do_the_new_thing(); @@ -111,14 +111,14 @@ If you want to use multiple SDK Keys in the same application, create only one _C | Parameters | Description | | -------------- | ------------------------------------------------------------------------------------------------------------ | | `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | -| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | | `default` | **REQUIRED.** This value will be returned in case of an error. | +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | ```rust let is_awesome_feature_enabled = client.get_value( "isAwesomeFeatureEnabled", // Setting Key - Some(User::new("#UNIQUE-USER-IDENTIFIER#")), // Optional User Object - false // Default value + false, // Default value + Some(User::new("#UNIQUE-USER-IDENTIFIER#")) // Optional User Object ).await; ``` @@ -139,16 +139,16 @@ that matches the type of the feature flag or setting you are evaluating. Please If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `default` will be returned. When relying on type inference and not explicitly specifying the type parameter, be mindful of potential type mismatch issues, especially with number types. -For example, `client.get_value("keyOfMyDecimalSetting", None, 0).await` will return `default` (`0`) instead of the actual value of the decimal setting because -the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", None, 0).await`, +For example, `client.get_value("keyOfMyDecimalSetting", 0, None).await` will return `default` (`0`) instead of the actual value of the decimal setting because +the compiler infers the type as `i64` instead of `f64`, that is, the call is equivalent to `client.get_value::("keyOfMyDecimalSetting", 0, None).await`, which is a type mismatch. To correctly evaluate a decimal setting, you should use: ```rust -let value = client.get_value("keyOfMyDecimalSetting", None, 0.0).await; +let value = client.get_value("keyOfMyDecimalSetting", 0.0, None).await; // -or- -let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; +let value = client.get_value("keyOfMyDecimalSetting", 0_f64, None).await; ``` ## Anatomy of `get_value_details()` @@ -158,12 +158,12 @@ let value = client.get_value("keyOfMyDecimalSetting", None, 0_f64).await; | Parameters | Description | | -------------- | ------------------------------------------------------------------------------------------------------------ | | `key` | **REQUIRED.** Setting-specific key. Set on _ConfigCat Dashboard_ for each setting. | -| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | | `default` | **REQUIRED.** This value will be returned in case of an error. +| `user` | Optional, _User Object_. Essential when using Targeting. [Read more about Targeting.](../advanced/targeting.mdx) | ```rust let user = User::new("#UNIQUE-USER-IDENTIFIER#"); // Optional User Object -let details = client.get_value_details("keyOfMyFeatureFlag", Some(user), false).await; +let details = client.get_value_details("keyOfMyFeatureFlag", false, Some(user)).await; ``` :::caution @@ -278,7 +278,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") .unwrap(); // The default user will be used in the evaluation process. -let value = client.get_value("keyOfMyFeatureFlag", None, false).await; +let value = client.get_value("keyOfMyFeatureFlag", false, None).await; ``` When a `user` parameter is passed to the evaluation methods, it takes precedence over the default user. @@ -292,7 +292,7 @@ let client = Client::builder("#YOUR-SDK-KEY#") let other_user = User::new("brian@example.com"); // other_user will be used in the evaluation process. -let value = client.get_value("keyOfMyFeatureFlag", Some(other_user), false).await; +let value = client.get_value("keyOfMyFeatureFlag", false, Some(other_user)).await; ``` You can also remove the default user by doing the following: From b926c5d3197224a11f25d2af396b2167992b22cc Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Thu, 13 Jun 2024 11:34:59 +0200 Subject: [PATCH 6/8] Add log example --- website/docs/sdk-reference/rust.mdx | 2 ++ website/versioned_docs/version-V1/sdk-reference/rust.mdx | 2 ++ 2 files changed, 4 insertions(+) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index 366f8e99..4b4bbd6a 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -692,6 +692,8 @@ INFO [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":" Date: Fri, 14 Jun 2024 16:58:39 +0200 Subject: [PATCH 7/8] get_all_details() -> get_all_value_details() --- website/docs/sdk-reference/rust.mdx | 6 +++--- website/versioned_docs/version-V1/sdk-reference/rust.mdx | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index 4b4bbd6a..daf8a3df 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -615,17 +615,17 @@ let user = User::new("#UNIQUE-USER-IDENTIFIER#"); let values_with_user = await client.get_all_values(Some(user)).await; ``` -## `get_all_details()` +## `get_all_value_details()` Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a [User Object](#user-object) is optional. ```rust let client = Client::new("#YOUR-SDK-KEY#").unwrap(); -let details = await client.get_all_details(None).await; +let details = await client.get_all_value_details(None).await; // invoke with User Object let user = User::new("#UNIQUE-USER-IDENTIFIER#"); -let details_with_user = await client.get_all_details(Some(user)).await; +let details_with_user = await client.get_all_value_details(Some(user)).await; ``` ## Cache diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index 2f971181..db53305e 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -615,17 +615,17 @@ let user = User::new("#UNIQUE-USER-IDENTIFIER#"); let values_with_user = await client.get_all_values(Some(user)).await; ``` -## `get_all_details()` +## `get_all_value_details()` Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a [User Object](#user-object) is optional. ```rust let client = Client::new("#YOUR-SDK-KEY#").unwrap(); -let details = await client.get_all_details(None).await; +let details = await client.get_all_value_details(None).await; // invoke with User Object let user = User::new("#UNIQUE-USER-IDENTIFIER#"); -let details_with_user = await client.get_all_details(Some(user)).await; +let details_with_user = await client.get_all_value_details(Some(user)).await; ``` ## Cache From 6d3de9730677a61830d9392be11fddf0f13832b3 Mon Sep 17 00:00:00 2001 From: Peter Csajtai Date: Fri, 14 Jun 2024 17:56:01 +0200 Subject: [PATCH 8/8] Add GH stars --- website/docs/sdk-reference/rust.mdx | 4 ++-- website/versioned_docs/version-V1/sdk-reference/rust.mdx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/website/docs/sdk-reference/rust.mdx b/website/docs/sdk-reference/rust.mdx index daf8a3df..8c405d72 100644 --- a/website/docs/sdk-reference/rust.mdx +++ b/website/docs/sdk-reference/rust.mdx @@ -4,6 +4,7 @@ title: Rust SDK Reference description: ConfigCat Rust SDK Reference. This is a step-by-step guide on how to use feature flags in your Rust applications. --- +[![Star on GitHub](https://img.shields.io/github/stars/configcat/rust-sdk.svg?style=social)](https://github.com/configcat/rust-sdk/stargazers) [![Build Status](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml) [![crates.io](https://img.shields.io/crates/v/configcat.svg?logo=rust)](https://crates.io/crates/configcat) [![docs.rs](https://img.shields.io/badge/docs.rs-configcat-66c2a5?logo=docs.rs)](https://docs.rs/configcat) @@ -304,11 +305,10 @@ client.clear_default_user(); ## Polling Modes The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. +[More about polling modes & caching](../advanced/caching.mdx). When no polling mode is specified upon SDK initialization, `AutoPoll` will be selected with a `60s` poll interval. -[More about polling modes.](../advanced/caching.mdx) - ### Auto polling (default) The _ConfigCat SDK_ downloads and stores the latest values automatically. The `Duration` parameter specifies how frequent the config JSON downloads will happen. diff --git a/website/versioned_docs/version-V1/sdk-reference/rust.mdx b/website/versioned_docs/version-V1/sdk-reference/rust.mdx index db53305e..4b6af3bd 100644 --- a/website/versioned_docs/version-V1/sdk-reference/rust.mdx +++ b/website/versioned_docs/version-V1/sdk-reference/rust.mdx @@ -4,6 +4,7 @@ title: Rust SDK Reference description: ConfigCat Rust SDK Reference. This is a step-by-step guide on how to use feature flags in your Rust applications. --- +[![Star on GitHub](https://img.shields.io/github/stars/configcat/rust-sdk.svg?style=social)](https://github.com/configcat/rust-sdk/stargazers) [![Build Status](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/configcat/rust-sdk/actions/workflows/ci.yml) [![crates.io](https://img.shields.io/crates/v/configcat.svg?logo=rust)](https://crates.io/crates/configcat) [![docs.rs](https://img.shields.io/badge/docs.rs-configcat-66c2a5?logo=docs.rs)](https://docs.rs/configcat) @@ -304,11 +305,10 @@ client.clear_default_user(); ## Polling Modes The _ConfigCat SDK_ supports 3 different polling mechanisms to acquire the setting values from _ConfigCat_. After latest setting values are downloaded, they are stored in the local cache, then all `get_value()` calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. +[More about polling modes & caching](../advanced/caching.mdx). When no polling mode is specified upon SDK initialization, `AutoPoll` will be selected with a `60s` poll interval. -[More about polling modes.](../advanced/caching.mdx) - ### Auto polling (default) The _ConfigCat SDK_ downloads and stores the latest values automatically. The `Duration` parameter specifies how frequent the config JSON downloads will happen.