Middleware
Middleware
Middleware runs your code around a router’s filters and handlers. Outer middleware runs once per update, before
anything in the router; inner middleware runs around each handler that matched. Both get a Next to pass the update
on.
Example
An admin guard that stops the update for everyone else, and times the handler:
use vaegram::handlers::{Next, UpdateContext};
use vaegram::prelude::*;
/// Provided to the handlers behind the guard.
#[derive(Clone)]
struct Admin(i64);
async fn ban(msg: Message, Dep(admin): Dep<Admin>) -> Result<()> {
msg.reply(format!("Banned on behalf of {}.", admin.0)).await?;
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let app = Client::builder("guard_bot", 12345, std::env::var("API_HASH").unwrap())
.bot_token(std::env::var("BOT_TOKEN").unwrap())
.start()
.await?;
let mut admin = Router::new();
admin.outer_middleware(|mut ctx: UpdateContext, next: Next| async move {
match ctx.user_id() {
Some(id) if id == 42 => {
ctx.provide(Admin(id));
next.run(ctx).await
}
// Returning without `next.run` keeps the update: later routes in this group don't see it.
_ => Ok(()),
}
});
admin.inner_middleware(|ctx: UpdateContext, next: Next| async move {
let started = std::time::Instant::now();
let result = next.run(ctx).await;
eprintln!("handled in {:?}", started.elapsed());
result
});
admin.message().handle(filters::command("ban"), ban);
app.include_router(admin);
app.run().await
}
How it works
Outer middleware
router.outer_middleware(f) runs on every update that reaches the router, for the kinds it has handlers for;
router.message().outer_middleware(f) adds one for a single kind, and makes the router take part in that kind even
without a handler. What the middleware does with Next decides who sees the update
(src/handlers/router.rs:68-80):
next.run(ctx).awaithands it to the router’s filters and handlers and gives back their result.- Returning without running
nextkeeps the update: the routes after this router in its group never get it. - Running
nextand having nothing match passes the update on unchanged: the routes after this router in its group get it as it arrived, without this middleware’sprovideorevent_mutchanges.
Inner middleware
router.inner_middleware(f) wraps each handler of the router and of the routers inside it whose filter matched,
after the outer middleware. Returning without next.run skips just that handler, which still takes its group’s turn.
A parent’s inner middleware runs outside its children’s (src/handlers/router.rs:82-86). The built-in
chat_action is one:
router.inner_middleware(chat_action(ChatAction::Typing));
The context
UpdateContext carries the event, the client and the values provided so far:
client(),kind(),chat_id(),user_id();event::<T>(),event_mut::<T>(), and the shortcutsmessage()andcallback_query();data(),provide(value)for handlers after this middleware (taken asDep<V>).
ctx.provide replaces a value of the same type; event_mut changes stay inside the router when nothing matches.
Order
Filters decide before the update is parsed where they can, so a router whose filters miss costs nothing. Then the
outer middleware in the order it was added (the first outermost, a parent’s before its children’s), the inner
middleware around the matched handler, and the handler. An Err from any of them goes to the router’s on_error,
and one that reaches the client stops the later groups for that update.
Common mistakes
- Ending an outer middleware with
Ok(())while wanting the update to continue: that is the “keep” outcome. Callnext.run(ctx).awaitand return its result. - Changing
ctxand expecting later routers to see it when nothing matched: they get the update as it arrived. - Using outer middleware for per-handler work: it runs even when no handler matches. Use inner middleware.
- Dropping the result of
next.run: errors stop at the middleware, andon_errornever sees them. - Adding middleware to a router that is never included: it never runs.