The Context
Introduction
Every request and console command your application handles runs in its own context, a Tokio task-local value that holds your application along with the values that belong to that request or command.
Deep inside your application, a function often needs a configuration value, a route's URL, or a service. Instead of passing the application down to every function that might need it, you may call helpers such as dust::config, dust::url::route, and dust::resolve from any function, and they read what they need from the context.
For example, any function in your application may build a user's profile URL without taking the application as an argument:
use crate::http::handlers::users;use crate::models::User;pub fn profile_url(user: &User) -> dust::Result<String> { dust::url::route(users::show, user.id)}Queued jobs, queued listeners, and scheduled tasks each run in a context of their own too, and so do your tests, when they take an Application argument.
These are the places a context exists, and what it carries:
| Place | Context | Carries values from the caller |
|---|---|---|
| An HTTP request | One per request | No; it starts fresh. |
| A console command | One per command | No; it starts fresh. |
| A queued job or queued listener | One per attempt | Yes, from the code that dispatched it. |
| A scheduled task | One per run | No; it starts fresh. |
A test with Application |
One per test | No; it starts fresh. |
A task spawned with dust::task::spawn |
The parent's context | Yes. |
A task spawned with tokio::spawn |
A new task with no context | No. Use task::spawn to keep it. |
Adding to the context
When you're reading logs, you often want to know which tenant or user a line came from. The context can hold values like these for you. Every log line written in the context carries them, so you can find every line a tenant's request logged. A middleware is a good place to add them:
use dust::http::{Next, middleware};use dust::prelude::*;#[middleware]pub async fn identify_tenant(request: Request, next: Next) -> Response { // `acme.example.com` is the `acme` tenant... let tenant = request.host().split('.').next().unwrap_or_default().to_owned(); dust::context::add("tenant", tenant); next.run(request).await}Adding a key again replaces its value. Any code that runs later in the request may read a value back with get, which returns None when the key has no value:
use dust::context;let tenant: Option<String> = context::get("tenant");You may also check for a key with context::has("tenant"), and remove it with context::forget("tenant").
When the request ends, dust-framework removes the values you added to its context. A queued job starts with the values of the code that dispatched it, so its log lines carry the same tenant as the request. When the job fails, its error is reported with those values and the ones the job added. To see how the values look in your log files, whether as plain text or JSON, check out the logging guide's section on adding context.
The context API is small:
| Function | Does |
|---|---|
add(key, value) |
Sets a value that appears in logs and error reports. |
get::<T>(key) |
Reads the value back, or None. |
has(key) |
Whether the key has a value. |
forget(key) |
Removes the key for the rest of the request. |
add_hidden, get_hidden, forget_hidden |
The same, for values that must stay out of logs. |
all() |
Every logged value, for a custom reporter. |
Values are typed at the point you read them: get("tenant") returns Option<String> because the call site asks for a String. A key set with another type reads as None rather than panicking, so keep one type per key.
Hidden values
For a value that only your own code needs, use add_hidden, which keeps the value out of the logs. Read it back with get_hidden, and remove it with forget_hidden:
use dust::context;context::add_hidden("plan", "pro");let plan: Option<String> = context::get_hidden("plan");Memoizing with once
use crate::models::User;#[dust::once]pub async fn user_count() -> dust::Result<u64> { User::query().count().await}The body runs once even when several callers ask at the same time. The result is only remembered for the current request, so the next request runs the body again. once remembers an error like any other result, so a failed query isn't retried until the next request.
Each caller gets a clone of the result, so the value must implement Clone. When it doesn't, or when it's large, such as a report built from thousands of rows, return it in an Arc. Every caller then shares the one value, and cloning the Arc only copies a pointer:
use std::sync::Arc;use crate::reports::SalesReport;#[dust::once]pub async fn sales_report() -> dust::Result<Arc<SalesReport>> { Ok(Arc::new(SalesReport::build().await?))}Keyed values
When the function takes arguments, once remembers a separate result for each set of arguments. Calling find_user(1) twice in a request queries the database once, while find_user(2) runs its own query and remembers its own result:
use crate::models::User;#[dust::once]pub async fn find_user(id: i64) -> dust::Result<Option<User>> { User::find(id).await}Arguments must be owned values that implement Hash, such as an i64 ID or a String. For example, pass user.id rather than a whole User, and slug.to_owned() rather than a &str.
Once closures
To memoize a value in the middle of a function, call dust::once with a closure, or dust::once_for with a key and a closure that receives it:
use crate::models::User;pub async fn find_user(id: i64) -> dust::Result<Option<User>> { dust::once_for(id, async |id| User::find(id).await).await}The closure can't capture variables, so pass whatever the value depends on as the key instead.
Spawned tasks
A task you spawn with tokio::spawn starts without the context, because task-local values don't carry over to a new task. A helper inside it panics with a message that names the helper:
`dust::url::to()` can only be used inside the application: while it handles a request or runs a command, in `Application::scope`, or in a task spawned with `dust::task::spawn`Use dust::task::spawn instead. It carries the current context and tracing span into the new task:
use dust::task;let handle = task::spawn(async { dust::url::to("/users") });let url = handle.await?;The task shares the context, so once still computes each value only once, and the task's log lines carry the values you've added. When you're ready to run more work at once, the concurrency and tasks guide shows how to run several operations at once, and how to run work in the background without making the user wait.