laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
Documentation
# The Context

- [Introduction]#introduction
- [Adding to the context]#adding-to-the-context
    - [Hidden values]#hidden-values
- [Memoizing with once]#memoizing-with-once
    - [Keyed values]#keyed-values
    - [Once closures]#once-closures
- [Spawned tasks]#spawned-tasks

<a name="introduction"></a>
## Introduction

Every request and console command your application handles runs in its own context, a [Tokio task-local](https://docs.rs/tokio/latest/tokio/macro.task_local.html) 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 `laravel::config`, `laravel::url::route`, and `laravel::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:

```rust
use crate::http::handlers::users;
use crate::models::User;

pub fn profile_url(user: &User) -> laravel::Result<String> {
    laravel::url::route(users::show, user.id)
}
```

Queued jobs, [queued listeners](events.md#queued-listeners), and scheduled tasks each run in a context of their own too, and so do your [tests](testing.md#unit-and-application-tests), when they take an `Application` argument.

<a name="adding-to-the-context"></a>
## 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](middleware.md) is a good place to add them:

```rust
use laravel::http::{Next, middleware};
use laravel::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();

    laravel::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:

```rust
use laravel::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, Laravel removes the values you added to its context. A [queued job](queues.md) 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](logging.md#adding-context).

<a name="hidden-values"></a>
### 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`:

```rust
use laravel::context;

context::add_hidden("plan", "pro");

let plan: Option<String> = context::get_hidden("plan");
```

<a name="memoizing-with-once"></a>
## Memoizing with once

Sometimes several parts of a request need the same value, such as a count that both the handler and a shared Inertia prop show. Rather than query it twice, mark an async function with `#[laravel::once]`. Its body runs once per request, and later calls get a clone of the first result. You may put these functions in any module, such as `src/models/mod.rs`, next to your models:

```rust
use crate::models::User;

#[laravel::once]
pub async fn user_count() -> laravel::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:

```rust
use std::sync::Arc;

use crate::reports::SalesReport;

#[laravel::once]
pub async fn sales_report() -> laravel::Result<Arc<SalesReport>> {
    Ok(Arc::new(SalesReport::build().await?))
}
```

<a name="keyed-values"></a>
### 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:

```rust
use crate::models::User;

#[laravel::once]
pub async fn find_user(id: i64) -> laravel::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`.

<a name="once-closures"></a>
### Once closures

To memoize a value in the middle of a function, call `laravel::once` with a closure, or `laravel::once_for` with a key and a closure that receives it:

```rust
use crate::models::User;

pub async fn find_user(id: i64) -> laravel::Result<Option<User>> {
    laravel::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.

<a name="spawned-tasks"></a>
## 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:

```text
`laravel::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 `laravel::task::spawn`
```

Use [`laravel::task::spawn`](tasks.md#spawned-tasks) instead. It carries the current context and tracing span into the new task:

```rust
use laravel::task;

let handle = task::spawn(async { laravel::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](#adding-to-the-context). When you're ready to run more work at once, the [concurrency and tasks guide](tasks.md) shows how to run several operations at once, and how to run work in the background without making the user wait.