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

# Rust SDK - Configuration

> NexusConfig field reference, TTL guidance, WifConfig overview, and Clone behaviour for the Rust SDK.

`NexusConfig` is a plain Rust struct holding every value required to construct a client. Pass it by value to `NexusClient::create`.

```rust theme={null}
use westyx_nexus::{NexusClient, NexusConfig};
use std::time::Duration;

let client = NexusClient::create(NexusConfig {
    api_key: std::env::var("NEXUS_API_KEY").unwrap_or_default(),
    endpoint: "https://<slug>.westyx.dev".to_string(), // required
    ttl: Some(Duration::from_secs(60)),                    // optional, default 60s
    wif: None,                                             // optional
})?;
```

## Field reference

| Field                    | Type                | Default | Description                                                                                                                                                                                                                                                                           |
| ------------------------ | ------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api_key`                | `String`            | -       | Raw `wxs_...` or `wxp_...` key. Sent verbatim in `X-Nexus-API-Key`. Pass an empty string when using WIF exclusively.                                                                                                                                                                  |
| `endpoint`               | `String`            | -       | Full service URL, e.g. `https://<slug>.westyx.dev`. Required. The slug embedded in the host is validated by the backend (Double-Gate).                                                                                                                                                |
| `ttl`                    | `Option<Duration>`  | `60s`   | Local cache TTL. After it elapses the next read serves the stale cache immediately and schedules a background refresh. `None` uses the default of 60 seconds.                                                                                                                         |
| `wif`                    | `Option<WifConfig>` | `None`  | Optional Workload Identity Federation config. When `Some`, the SDK exchanges a workload OIDC token for a Nexus session JWT. See [Workload identity](workload-identity).                                                                                                               |
| `sse_reconnect_cooldown` | `Option<Vec<u64>>`  | `None`  | Schedule for reconnecting SSE after falling back to TTL polling. Unit: **minutes**. `None` = default `[5, 10, 20, 40, 60]` min. Single-element = fixed interval. Multi-element = custom schedule (stays at last value). Empty vec falls back to default. Values below 1 clamped to 1. |

## API key types

| Prefix    | Access                                 | What is synced                                           |
| --------- | -------------------------------------- | -------------------------------------------------------- |
| `wxs_...` | Full - all configs, secrets, and flags | `configs`, `secrets`, and `flags` populated              |
| `wxp_...` | Restricted - only configs and flags    | `secrets` field is **entirely absent** from the response |

<Warning>
  Calling `get_secret(...)` with a public key returns `NexusError::PublicKeyRestricted` synchronously, before any network call.
</Warning>

## Where to keep the API key

The conventional Rust pattern is environment variables:

```rust theme={null}
NexusConfig {
    api_key: std::env::var("NEXUS_API_KEY").unwrap_or_default(),
    endpoint: std::env::var("NEXUS_URL").expect("NEXUS_URL not set"),
    ..Default::default()
}
```

The SDK never logs the raw key value. Log lines reference key type only:

```
nexus: client ready (key_type=sk, ttl=60s)
```

## Choosing the TTL

The TTL is a trade-off between staleness window and redundant network traffic. With SSE enabled (`client.run_stream()`), **changes propagate within milliseconds regardless of the TTL** - the TTL is only a safety net if the stream falls back to polling.

| Use case                                     | Suggested TTL                       |
| -------------------------------------------- | ----------------------------------- |
| Frequently-changing flags, latency-sensitive | `Duration::from_secs(30)`           |
| Standard configs with SSE                    | `Duration::from_secs(60)` (default) |
| Stable production secrets                    | `Duration::from_secs(300)`          |
| Boot-time only, never rechecked              | `Duration::from_secs(3600)`         |

<Info>
  When SSE is connected, the effective TTL is clamped to at least 60 s internally - there is no benefit to polling more aggressively when the stream already pushes events the moment they happen.
</Info>

## WifConfig

`WifConfig` configures Workload Identity Federation. The `wif` field is `None` by default; WIF is active only when it is `Some`.

```rust theme={null}
use westyx_nexus::{NexusConfig, WifConfig};

NexusConfig {
    api_key: String::new(), // empty - WIF provides auth
    endpoint: "https://<slug>.westyx.dev".to_string(),
    ttl: None,
    wif: Some(WifConfig {
        enabled: true,
        provider: "auto".to_string(), // auto-detect from environment
        token_source: None,           // use built-in provider
        audience: None,               // GCP/Azure-IMDS audience
        aws_region: None,             // aws_iam STS region
    }),
}
```

### WifConfig field reference

| Field          | Type                                                                | Default  | Description                                                                                                                                                                                                                         |
| -------------- | ------------------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`      | `bool`                                                              | `false`  | When `true`, the SDK uses WIF instead of the static `api_key`.                                                                                                                                                                      |
| `provider`     | `String`                                                            | `"auto"` | One of `"kubernetes"`, `"aws"`, `"aws_iam"`, `"gcp"`, `"azure"`, or `"auto"`. `"auto"` probes the environment in order (`aws_iam` is never auto-detected).                                                                          |
| `token_source` | `Option<Box<dyn Fn() -> Result<String, NexusError> + Send + Sync>>` | `None`   | Custom token-fetching function. When `Some`, it overrides `provider`. The function must return a workload OIDC JWT string.                                                                                                          |
| `audience`     | `Option<String>`                                                    | `None`   | Audience requested from GCP/Azure. **Required on the Azure IMDS path** (must be `api://<client-id>`; the generic default is refused). Defaults to `westyx-nexus` for GCP; informational for file-based providers. *(v0.9.0-beta.1)* |
| `aws_region`   | `Option<String>`                                                    | `None`   | STS region for the `aws_iam` provider. When `None`, resolved from the standard AWS region chain (env, config) with an EC2 IMDS fallback. Ignored by other providers. *(v0.9.0-beta.1)*                                              |

See [Workload identity](workload-identity) for the full WIF setup guide.

## Clone behaviour

`NexusClient` implements `Clone`. Cloning is **cheap** - it increments an `Arc` reference count and shares the same internal cache state. All clones read from and write to the same snapshot.

```rust theme={null}
let client_a = client.clone(); // cheap - Arc bump
let client_b = client.clone();

// Both see the same cache; a sync on any clone updates all of them.
std::thread::spawn(move || {
    let val = client_a.get_config("feature.key");
});
```

This makes it straightforward to share a single `NexusClient` across actix-web extractors, axum `State`, or a thread pool - just clone once per handler and move the clone in.

<Note>
  The `Drop` implementation only runs cleanup (temp file removal for file-type secrets) when the **last** clone is dropped. Dropping individual clones does not clean up shared resources.
</Note>
