# Deployment

How a vaegram client takes updates in production, stops cleanly, and avoids fighting a second copy of itself.

A deployed bot is a process that stays connected for weeks. What keeps it that way is how it gets updates, how it shuts down, and how many copies run.

## Example

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

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

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

    bot.run().await
}
```

`run` returns `Ok(())` after `stop`, and `Error::Disconnected` when the connection ends first.

## How updates arrive

| Mode | How updates reach the handlers | When to use it |
|---|---|---|
| MTProto (default) | Telegram pushes updates on the connection; `run` dispatches them | user accounts, MTProto bots |
| Bot API polling | `run` long-polls `getUpdates` | a Bot API bot that can reach `api.telegram.org` |
| Bot API webhook | Telegram POSTs to your HTTPS URL; a `Webhook` dispatches them | a Bot API bot behind a public HTTPS proxy |

The first two are the same call, `run`. In Bot API mode a webhook replaces the poll: while one is set, `Client::run` gets Telegram's 409 error instead of updates.

## Webhooks

Webhook mode needs the `bot-api` feature, and the built-in server needs `webhook-server`. The flow is always: make a receiver with a secret, register the public URL, then feed it requests.

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

#[tokio::main]
async fn main() -> Result<()> {
    let bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
        .bot_api(std::env::var("BOT_TOKEN").expect("BOT_TOKEN"))
        .start()
        .await?;

    let secret = std::env::var("WEBHOOK_SECRET").expect("WEBHOOK_SECRET");
    let webhook = bot.webhook(secret)?;
    webhook.register("https://bot.example.com/telegram").await?;

    webhook.serve("127.0.0.1:8080").await
}
```

The API id and hash are not used in Bot API mode, but `Client::builder` still takes them.

- **The secret** is 1 to 256 characters of `A-Z`, `a-z`, `0-9`, `_` and `-`. Keep it in the environment or a secret store. The receiver compares it in constant time; `serve` rejects a request before reading its body.
- **The URL** must be HTTPS, on port 443, 80, 88 or 8443. `serve` speaks plain HTTP, so it belongs behind a reverse proxy that terminates TLS: bind it where only the proxy reaches it and register the proxy's public URL.
- **A self-signed certificate** is uploaded with the webhook: `.certificate(pem_bytes)` on the request `register` returns. `.ip_address("203.0.113.10")` pins where Telegram sends requests, and `.max_connections(40)` sets how many it sends at once (1 to 100).
- **`get_webhook_info`** reports the URL, `pending_update_count` and `last_error_message`, which is the first thing to read when deliveries stop.

### Your own HTTP server

`Webhook::handle` takes one request's body and headers and returns a `WebhookResponse`; answer the request with its `status()`. Drive the handlers with `webhook.run().await` (it is `Client::run`, fed by the webhook) and mount `handle` in whatever server you already run.

```no_run
# async fn f(webhook: vaegram::bot_api::Webhook, body: Vec<u8>, token: Option<&str>) -> vaegram::Result<()> {
let headers = token.into_iter().map(|value| ("X-Telegram-Bot-Api-Secret-Token", value));
let answer = webhook.handle(&body, headers).await;
match answer.status() {
    200 => {} // queued for the handlers, or already taken
    401 => {} // wrong or missing secret; nothing was queued
    _ => {}   // 503: no run is taking updates, or the queue stayed full
}
# Ok(()) }
```

`serve` is a small HTTP/1.1 server around the same path: it accepts POST only (405 otherwise), checks the secret before reading the body (401), caps a body at 4 MiB (413), serves 256 connections at once, and answers 200 as soon as an update is queued, so a slow handler never causes a redelivery.

To go back to polling, `bot.delete_webhook().await?;` and then `run`.

## Graceful shutdown

`run_until_signal` stops on Ctrl-C or, on Unix, SIGTERM, which is what containers and service managers send. It calls `stop`, so `run` finishes the handlers already running and returns `Ok(())`.

```no_run
# async fn f(bot: vaegram::Client) -> vaegram::Result<()> {
bot.run_until_signal().await?; // Ctrl-C or SIGTERM calls stop()
bot.close().await;             // waits for the final save before the process exits
# Ok(()) }
```

- `stop_with_timeout(d)` bounds that wait: handlers still running at the deadline are cancelled and reported as `Error::Timeout`.
- `run` saves the update state as it returns; `close().await` is what flushes and closes the storage. Await it before `std::process::exit` or `Runtime::shutdown_background`, which do not wait for a save a plain drop starts in the background.
- Returning from `main`, `#[tokio::main]` included, waits for that save.

## One instance per session

The default `FileStorage` keeps `<name>.session` and holds `<name>.session.lock` while the client is open. A second client on the same file, in this process or another, fails with `ResourceBusy` instead of writing interleaved records.

That lock does not protect you from running the same login on two machines: copying the session file and starting both gets the auth key revoked by Telegram (`Error::is_auth_key_duplicated`), and both clients must log in again. One process per login, or log in separately on each.

In Bot API mode Telegram allows one consumer of a bot's updates: a second poller, or a poll while a webhook is set, gets 409.

## Behind a proxy

`ClientBuilder::proxy` takes a parsed `Proxy`. Any address or link `Proxy` understands works, including `tg://proxy`, `tg://socks` and `t.me/proxy` links.

```no_run
use vaegram::connection::Proxy;

# async fn f() -> vaegram::Result<()> {
let proxy: Proxy = "tg://socks?server=127.0.0.1&port=1080".parse()?;
let _bot = vaegram::Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
    .bot_token("123456:ABC-DEF")
    .proxy(proxy);
# Ok(()) }
```

- SOCKS5, SOCKS4 and HTTP CONNECT are built in; HTTP CONNECT sends Basic credentials in the clear.
- An MTProxy goes through `.proxy(Proxy::MtProxy { .. })`; the secret picks padding or fake TLS.
- On a network that only lets HTTPS out, the `web-proxy` feature adds `Proxy::Web`, an MTProxy stream carried in HTTPS requests to a relay (`tg://webproxy` links). The `websocket` feature is the other way out: `.websocket()` connects over TLS to `web.telegram.org`.

## Common mistakes

- Registering `http://` or a non-standard port. Telegram only posts to HTTPS on 443, 80, 88 and 8443.
- Calling `webhook.serve` before `register`, or without a running `run`: every request is answered 503.
- Using `run_until_ctrl_c` in a container. SIGTERM ends the process without a clean stop; use `run_until_signal`.
- Skipping `close().await` before `std::process::exit`, and losing the last update state.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/bot_api/struct.Webhook.html) for `Webhook` and `WebhookResponse`.
- [Receiving updates](/docs/receiving-updates.md) for handlers and the update loop.
- [Bot API mode vs MTProto](/docs/bot-api-vs-mtproto.md) for what each transport supports.
- [Sessions and storage](/docs/sessions-and-storage.md) for the session file and its lock.