# Sessions and storage

Where a client keeps its login, its update position and the peers it has met, and how to move that from one process to another.

"Session" means the saved auth key and where updates resume. vaegram stores it in a file by default; any `Storage` engine can replace the file.

## Example

```no_run
use vaegram::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let bot = Client::builder("echo", 12345, "0123456789abcdef0123456789abcdef")
        .bot_token("123456:ABC-DEF")
        .workdir("/var/lib/mybot")
        .start()
        .await?;

    bot.on_message(filters::command("start"), |msg| async move {
        msg.answer("Ready.").await?;
        Ok(())
    });

    bot.run().await
}
```

The first run logs in and writes `/var/lib/mybot/echo.session`; later runs log in from it.

`Client::is_signed_in()` answers whether the client already holds a login, without a request to Telegram: false
before a login, true once one is cached.

## What a session holds

- **The login**: the data center id, the 256-byte auth key, the api id, the account's user id, and the bot and test-server flags.
- **The update state**: the account's `pts`, `qts`, `date` and `seq`, plus each channel's `pts`. `run` resumes from it, which is how a restart does not miss or repeat updates.
- **Peers**: the id, access hash, known usernames and phone number of every user and chat the client met, so it can address them again without a lookup.

## The session file

`FileStorage`, the default, keeps all three in one `<name>.session` file. The name comes from `Client::builder` and may contain a directory: `"bots/echo"` keeps `bots/echo.session` under `workdir` (the working directory if unset).

- The file is created private to the user (0600 on Unix).
- Each save appends a record; the file is rewritten whole once the appended bytes outgrow what it holds.
- A torn last record from a crash is ignored; the records before it stand.
- While a client has the file open it holds `<name>.session.lock` in the same directory. A second client on the same file fails with `ResourceBusy`, even in another process. The lock goes with the process, so a crash leaves no stale lock, only the empty `.lock` file.

## Session strings

`Client::export_session_string` renders the login as one `VAE_…` line. It is the auth key: anyone who has it is logged in as the account.

```no_run
use vaegram::prelude::*;

# async fn f(bot: &Client) -> Result<()> {
let line = bot.export_session_string();

let other = Client::builder("copy", 12345, "0123456789abcdef0123456789abcdef")
    .session_string(line)
    .bot_token("123456:ABC-DEF")
    .start()
    .await?;
# let _ = other; Ok(()) }
```

`vaegram::storage::session_string::parse` reads one back without a client, and fails with a message meant for the user:

```rust
use vaegram::storage::session_string;

fn main() {
    match session_string::parse("VAE_not-a-real-string") {
        Ok(data) => println!("data center {}", data.dc_id),
        Err(why) => eprintln!("{why}"),
    }
}
```

The parser also accepts a few layouts other tools write: `WZ_`-prefixed strings, unprefixed fixed-size strings, and the address-first form. The exporter never writes those, only reads them. A string in a layout it cannot use fails with a message meant for the user, such as an old fixed layout whose generation byte it does not know.

## Choosing storage

Three builder methods choose where the session lives, and the last of them called wins. `workdir` only moves the default file.

```rust
use vaegram::prelude::*;
use vaegram::storage::MemoryStorage;

let _bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
    .storage_engine(MemoryStorage::new()); // the same as .in_memory()
```

- `storage_engine(engine)` keeps the login, state and peers in any `Storage`; it runs on a thread of the client's own, so an engine may block.
- `session_string(s)` keeps them in memory and starts from `s`. The login is then never written, so the next run needs the string again.
- `in_memory()` keeps everything in memory and writes nothing; without an exported session string the next run logs in again.
- `workdir(dir)` only moves the default file; it is ignored once another storage is chosen.

The `Storage` trait itself is small: `open`, `close`, `delete`, `load_session`, `save_session`, `load_state`, `save_state`, `update_peers`, `get_peer_by_id`, `get_peer_by_username`, `get_peer_by_phone_number`, `export_peers`, `clear_peers`. Implement it to keep a session anywhere.

### Engines

| Engine | Feature | Constructor | Keeps it in |
|---|---|---|---|
| `FileStorage` | none (default) | `FileStorage::new(name)` | the `.session` file above |
| `MemoryStorage` | none | `MemoryStorage::new()` | memory only |
| `SqliteStorage` | `sqlite` | `SqliteStorage::new(path)` | a SQLite database, WAL mode, schema version 8 |
| `RedbStorage` | `redb` | `RedbStorage::new(path)` | a redb file, one process per file |
| `RedisStorage` | `redis` | `RedisStorage::new(url, name)` | Redis keys under `vaegram:<name>` |
| `MongoStorage` | `mongodb` | `MongoStorage::new(uri, name)` | a Mongo database named after the session |
| `PostgresStorage` | `postgres` | `PostgresStorage::new(config, tls, name)` | a schema `name` in that database |
| `S3Storage` | `s3` | `S3Storage::from_env(bucket, key)` | one S3-compatible object |
| `VaultStorage` | `vault` | `VaultStorage::new(addr, token, mount, path)` | a HashiCorp Vault secret |

Details that bite:

- **SQLite** opens databases in the schema other MTProto tools use (version 8), so an existing `.session` database opens here; it is migrated in place, so keep a copy.
- **Redis** needs `maxmemory-policy noeviction`; an evicted session key is a lost login. On a cluster, give the prefix a hash tag so its keys share a slot.
- **Postgres** creates its schema and holds a lock on it: one client per schema, a second gets `ResourceBusy` until the first closes.
- **S3** uploads conditionally (`If-Match`) and refuses to overwrite an object another client wrote. State and peers upload at most every 30 seconds and on close.
- **Vault** stores one session string in a secret; every write names the version it read. The token is not renewed, so it must outlive the client.

## Closing

The update state is saved when `run` returns or its future is dropped, and while it runs within about 10 seconds of
moving. The storage closes on `close().await`, on `disconnect()`, or when the last clone of the client is dropped (in
the background, without blocking the runtime). `close` waits for the final save once no `run` owns the client;
`disconnect()` does the same work but blocks the thread it runs on for up to 10 seconds. Await `close` after `run`
returns and before opening the same session again in the same process, or before `std::process::exit`.

## Common mistakes

- Copying a `.session` file to a second machine and running both. Telegram revokes the duplicated auth key (`AUTH_KEY_DUPLICATED`); log in separately instead.
- Committing a `.session` file or a session string. Both are the login.
- Using `in_memory()` and expecting peers or the login after a restart.
- Setting `workdir` while another storage is chosen.
- Running two clients on one Postgres schema, or two processes on one redb file.
- Passing a SQLite path without an extension expecting one to be added; `SqliteStorage::new` takes the path as given.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/storage/index.html) for `Storage`, `FileStorage` and `SessionData`.
- [Your first bot](/docs/first-bot.md) for the login flow this page shortens.
- [Deployment](/docs/deployment.md) for the lock and one-instance rules in a running service.
- [Migration 0.3 to 0.4](/docs/migration-03-to-04.md) for what changed in storage.