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

# Initialization & lifecycle

> The MusterBox SDK lifecycle — initialize, start, authenticate, refresh, logout, shutdown.

The SDK is an explicit state machine. You drive it through well-defined steps,
and every step reports its result through stable errors and status.

## The lifecycle

```text theme={"dark"}
Uninitialized ──initialize──▶ Stopped ──start──▶ Running
                                                    │
                             ┌───────────authenticate──▶ Authenticated
                             ▼                            │
                         refresh ◀─────────────────── refresh_session
                             │                            │
                             ▼                            ▼
                         logout ────▶ Running          logout (session revoked)
                                                   
 Stopped ──shutdown──▶ Shutdown (resources released)
```

## Initialize

Parsing and validating configuration happens here. Invalid configuration fails
fast — nothing is sent over the network.

```rust theme={"dark"}
use musterbox_sdk::{MusterBoxSdk, MusterBoxConfig};

let config = MusterBoxConfig::from_env()?;
let sdk = MusterBoxSdk::initialize(config)?;
```

Web (browser):

```ts theme={"dark"}
import { createMusterBox } from "@musterbox/sdk-js";
const box = createMusterBox({
  gameId: "my-arena-game",
  gameKey: "gk_...",
  environment: "sandbox",
});
box.addEventListener("ready", () => { /* now safe to start */ });
```

Once initialized the SDK reports `Stopped`. Nothing is scheduled until
`start`.

## Start

Starts the worker machinery (event flush scheduler, realtime poller, wallet
stream). In `Threaded` runtime mode a background thread is spawned; in
`Manual` mode you drive progress by calling `tick`.

```rust theme={"dark"}
sdk.start();
```

## Authenticate

Exchanges credentials (or a persisted token) for a backend session. See
[Authentication](/sdk/authentication).

```rust theme={"dark"}
let player = sdk.authenticate("player@example.com", "secret")?;
```

The SDK owns the resulting credentials: access token, refresh token, expiry,
session id. Your game never touches the raw tokens.

## Refresh

The SDK rotates tokens automatically when the access token nears expiry,
using `POST /api/v1/auth/validate` with the refresh token. You can also
trigger a manual refresh:

```rust theme={"dark"}
sdk.refresh_session()?;
```

## Logout

Revokes the server-side session and clears local credentials.

```rust theme={"dark"}
sdk.logout()?;
```

## Shutdown

Releases the runtime. `shutdown_timeout_ms` (default 5000 ms) bounds the
graceful drain before resources are freed.

```rust theme={"dark"}
sdk.shutdown();
```

`shutdown` is idempotent and safe to call from any thread.

## Runtime options

| Option                  | Meaning                                                                |
| ----------------------- | ---------------------------------------------------------------------- |
| `RuntimeMode::Threaded` | Background worker drives timers and flushes (default for most engines) |
| `RuntimeMode::Manual`   | You call `tick()` with a `TickBudget` each frame                       |
| `TickBudget`            | Max commands/timers/elapsed-ms per tick — keeps a game frame honest    |

Single-threaded engines (Unity, Godot main thread, web) generally prefer
`Manual`, letting the SDK process bounded work per frame.

<Note>
  The blocking variants of SDK calls run on their own current-thread runtime.
  Do not call blocking variants from inside another Tokio runtime context.
</Note>
