Alexander Yurchenko

Async and shared state in Laravel Rust

Created
Updated
Author
Alexander Yurchenko

Create a ticket with POST /api/tickets, then read it back with a regular GET request. Both handlers need the same store. In the validation lesson, POST prepared the title for a preview. Here the same title becomes part of a new record.

Register the store

In the lesson on dependencies, main chose the formatter and passed it to a service. Here configure assembles the application. with_services runs the registration, and services.instance(TicketStore::new()) puts a ready-to-use instance in the Laravel Rust container. Each handler declares its dependency through Inject<TicketStore>. This extractor gives the handler shared access to the instance through an Arc. The Mutex inside TicketStore protects changes to the records.

Continue with your project from the validation lesson. Keep the manifest, lockfile, local settings, and src/main.rs entrypoint. Replace the entire src/app.rs file.

Download the exact Cargo.lock and save it as Cargo.lock in the demo project root. All three lessons use this file. Pass --locked so Cargo keeps the resolved versions.

RUST
use laravel::foundation::ApplicationBuilder;
use laravel::{Application, inertia, model};

use crate::http::middleware::{HandleInertiaRequests, example_middleware};
use crate::models::User;
use crate::routes;
use crate::routes::api::TicketStore;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        // All handlers in this application share one store instance.
        .with_services(|services| {
            services.instance(TicketStore::new());
        })
        .with_migrations(laravel::db::migrations!("database/migrations"))
        .with_schema(laravel::db::schema!("database/schema"))
        .with_auth(|auth, _| {
            auth.session::<model::Users<User>>();
        })
        .with_routing(|routing, _| {
            routing
                .web(routes::web::routes)
                .api(routes::api::routes)
                .channels(routes::channels::routes)
                .health("/up");
        })
        .with_middleware(|middleware, _| {
            middleware.web(|web| {
                web.append(inertia::middleware(HandleInertiaRequests))
                    .append(example_middleware);
            });
        })
}

pub fn create() -> Application {
    configure().create()
}

Connect reads and writes

Replace the entire src/routes/api.rs file. GET reads from the store. The new POST validates the title before calling insert. The body extractor Json<CreateTicket> goes last. The only value read from the client's JSON is title. The server assigns the ID and sets the status to open. The earlier preview route remains available separately.

RUST
mod store;

pub(crate) use store::TicketStore;

use laravel::container::Inject;
use laravel::http::middleware::LimitBody;
use laravel::http::{Created, Json, Query};
use laravel::routing::{Params, Router};
use laravel::validation::{InvalidInput, Validate};
use laravel::{Result, abort_with};
use serde::{Deserialize, Serialize};
use serde_json::json;

pub fn routes(route: &mut Router) {
    route.get("/version", async || Json(json!({ "laravel": laravel::VERSION })));
    route.get("/tickets", index);
    route.get("/tickets/{id}", show);
    route
        .post("/tickets", create)
        .middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
    route
        .post("/tickets/preview", preview)
        .middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum Status {
    Open,
    Closed,
}

struct Ticket {
    id: u32,
    title: String,
    status: Status,
}

#[derive(Debug, Serialize)]
struct TicketView {
    id: u32,
    title: String,
    status: Status,
}

impl From<&Ticket> for TicketView {
    fn from(ticket: &Ticket) -> Self {
        Self {
            id: ticket.id,
            title: ticket.title.clone(),
            status: ticket.status,
        }
    }
}

fn seed_tickets() -> Vec<Ticket> {
    vec![
        Ticket {
            id: 1,
            title: "Reset password".into(),
            status: Status::Open,
        },
        Ticket {
            id: 2,
            title: "Update invoice".into(),
            status: Status::Closed,
        },
    ]
}

#[laravel::query]
struct TicketQuery {
    // Keep an unknown nonempty value available for an explicit 400.
    status: Option<String>,
}

impl TicketQuery {
    fn filter(&self) -> Result<Option<Status>> {
        match self.status.as_deref() {
            None => Ok(None),
            Some("open") => Ok(Some(Status::Open)),
            Some("closed") => Ok(Some(Status::Closed)),
            Some(_) => Err(abort_with(400, "Status must be open or closed.")),
        }
    }
}

async fn index(store: Inject<TicketStore>, Query(query): Query<TicketQuery>) -> Result<Json<Vec<TicketView>>> {
    Ok(Json(store.list(query.filter()?)?))
}

async fn show(store: Inject<TicketStore>, Params(id): Params<u32>) -> Result<Json<TicketView>> {
    positive_id(id)?;
    let ticket = store.get(id)?.ok_or_else(|| abort_with(404, "Ticket not found."))?;
    Ok(Json(ticket))
}

async fn create(store: Inject<TicketStore>, Json(input): Json<CreateTicket>) -> Result<Created<TicketView>> {
    // If title validation fails, insertion never starts.
    Ok(Created(store.insert(input.validated_title()?)?))
}

fn positive_id(id: u32) -> Result<()> {
    if id == 0 {
        return Err(abort_with(400, "Ticket ID must be positive."));
    }
    Ok(())
}

const TICKET_BODY_LIMIT: usize = 4096;
const MAX_TITLE_LENGTH: usize = 120;

#[derive(Deserialize, Validate)]
struct CreateTicket {
    title: String,
}

#[derive(Serialize)]
struct TicketPreview {
    title: String,
}

async fn preview(Json(input): Json<CreateTicket>) -> Result<Json<TicketPreview>> {
    Ok(Json(TicketPreview {
        title: input.validated_title()?,
    }))
}

impl CreateTicket {
    fn validated_title(&self) -> Result<String> {
        let title = self.title.trim();
        let problem = if title.is_empty() {
            "Enter a ticket title."
        } else if title.chars().count() > MAX_TITLE_LENGTH {
            "The title must have at most 120 Unicode scalar values."
        } else {
            return Ok(title.to_owned());
        };
        Err(InvalidInput::new().with("title", problem).into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ticket_zero_fails_the_domain_check() {
        assert!(positive_id(1).is_ok());
        assert_eq!(positive_id(0).expect_err("zero").status(), 400);
    }

    #[test]
    fn title_validation_counts_trimmed_unicode_scalars() {
        let title = "🦀".repeat(120);
        let valid = CreateTicket {
            title: format!("  {title}  "),
        };
        assert_eq!(valid.validated_title().expect("120 scalars"), title);
        let invalid = CreateTicket {
            title: format!("{title}🦀"),
        };
        assert_eq!(invalid.validated_title().expect_err("121 scalars").status(), 422);
        let blank = CreateTicket {
            title: "\u{00a0}\t".into(),
        };
        assert_eq!(blank.validated_title().expect_err("blank").status(), 422);
    }
}

Create src/routes/api/store.rs. Its state holds the vector and the last issued ID. After taking the lock, insert checks the limit of 32 records, including the two seed records, and calculates the next ID with checked_add. Either failure returns before insertion. The same lock protects inserting the record and updating the counter. A full store returns 409. An exhausted ID range returns a generic 500. If a thread panics while holding the lock, the mutex can become poisoned. The example then also returns a generic 500 and leaves the potentially inconsistent data untouched.

A read returns an owned TicketView or a vector of those views. In the lesson on borrowing, a function returned a reference to the original data. Here the store copies the ID and status, clones the title, and releases the lock before serialization.

RUST
use std::sync::{Mutex, MutexGuard};

use laravel::{Result, abort, abort_with};

use super::{Status, Ticket, TicketView, seed_tickets};

const MAX_TICKETS: usize = 32;

pub(crate) struct TicketStore {
    state: Mutex<State>,
}

struct State {
    tickets: Vec<Ticket>,
    last_id: u32,
}

impl TicketStore {
    pub(crate) fn new() -> Self {
        let tickets = seed_tickets();
        let last_id = tickets.iter().map(|ticket| ticket.id).max().unwrap_or(0);
        Self {
            state: Mutex::new(State { tickets, last_id }),
        }
    }

    fn lock(&self) -> Result<MutexGuard<'_, State>> {
        // After a panic while holding the lock, do not use state that may have been partially updated.
        self.state.lock().map_err(|_| abort(500))
    }

    // Return owned values so serialization happens after the lock is released.
    pub(super) fn list(&self, status: Option<Status>) -> Result<Vec<TicketView>> {
        let state = self.lock()?;
        Ok(state
            .tickets
            .iter()
            .filter(|ticket| status.is_none_or(|status| ticket.status == status))
            .map(TicketView::from)
            .collect())
    }

    pub(super) fn get(&self, id: u32) -> Result<Option<TicketView>> {
        let state = self.lock()?;
        Ok(state
            .tickets
            .iter()
            .find(|ticket| ticket.id == id)
            .map(TicketView::from))
    }

    pub(super) fn insert(&self, title: String) -> Result<TicketView> {
        // One lock protects the capacity check, ID assignment, and insertion.
        let mut state = self.lock()?;
        if state.tickets.len() >= MAX_TICKETS {
            return Err(abort_with(409, "Ticket store is full."));
        }
        let id = state.last_id.checked_add(1).ok_or_else(|| abort(500))?;
        let ticket = Ticket {
            id,
            title,
            status: Status::Open,
        };
        let view = TicketView::from(&ticket);
        // Keep the ID and its record in the same critical section.
        state.tickets.push(ticket);
        state.last_id = id;
        Ok(view)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exhausting_ids_leaves_records_and_last_id_intact() {
        let store = TicketStore::new();
        store.state.lock().expect("unpoisoned").last_id = u32::MAX - 1;
        let last = store.insert("Last ID".into()).expect("one ID remains");
        assert_eq!(last.id, u32::MAX);
        assert_eq!(
            store.insert("Overflow".into()).expect_err("no ID remains").status(),
            500
        );
        let state = store.state.lock().expect("unpoisoned");
        assert_eq!(state.last_id, u32::MAX);
        assert_eq!(state.tickets.len(), 3);
        assert_eq!(
            state.tickets.last().map(|ticket| ticket.title.as_str()),
            Some("Last ID")
        );
    }

    #[test]
    fn capacity_rejection_does_not_consume_an_id() {
        let store = TicketStore::new();
        for _ in 2..MAX_TICKETS {
            store.insert("New ticket".into()).expect("space remains");
        }
        let err = store.insert("Overflow".into()).expect_err("full");
        assert_eq!(err.status(), 409);
        let state = store.state.lock().expect("unpoisoned");
        assert_eq!(state.tickets.len(), MAX_TICKETS);
        assert_eq!(state.last_id, 32);
    }

    #[test]
    fn a_poisoned_store_returns_an_internal_error() {
        let store = TicketStore::new();
        let unwind = std::panic::catch_unwind(|| {
            let _guard = store.state.lock().expect("unpoisoned");
            panic!("test-only panic while locked");
        });
        assert!(unwind.is_err());
        assert_eq!(store.list(None).expect_err("poisoned").status(), 500);
        assert_eq!(store.get(1).expect_err("poisoned").status(), 500);
        assert_eq!(store.insert("Unavailable".into()).expect_err("poisoned").status(), 500);
    }

    #[test]
    fn an_owned_snapshot_stays_unchanged_after_insertion() {
        let store = TicketStore::new();
        let before = store.list(None).expect("snapshot");
        assert_eq!(store.insert("New ticket".into()).expect("inserted").id, 3);
        assert_eq!(before.len(), 2);
        assert_eq!(store.list(None).expect("new snapshot").len(), 3);
    }
}

Await an asynchronous operation

Calling an async fn produces a future. An .await expression obtains the result when the future is ready. If the operation is still pending, the runtime can run other tasks. In the API, the vector operations are short and run under a regular std::sync::Mutex. The store methods have no .await, and they hold the lock only while working with the data. Move long blocking work off the async task threads, for example with spawn_blocking. If a shared resource really needs to be held across an await, consider tokio::sync::Mutex and work out how long callers will need to hold it.

Save the separate example in examples/read_fixture.rs to see an .await in use. Tokio reads a small local file, and the program prints the line once it has the result. The file-reading example uses Tokio directly.

RUST
#[tokio::main]
async fn main() -> std::io::Result<()> {
    let title = tokio::fs::read_to_string("examples/ticket-title.txt").await?;
    print!("{title}");
    Ok(())
}

Save this line in examples/ticket-title.txt with a final newline.

TEXT
Reset password

To check the read, run cargo run --locked --offline --example read_fixture. The program prints Reset password.

Verify creation and concurrent requests

Run these commands from the demo project root. After fetching dependencies, the build uses the local cache. The server reports the selected port. Use that port for requests to 127.0.0.1 and press Ctrl+C to stop the server.

BASH
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$PWD/target/build"
cargo fmt --check
cargo check --locked --offline --all-targets
cargo test --locked --offline --lib
cargo build --locked --offline
cargo run --locked --offline --example read_fixture
./target/debug/laravel-rust-skeleton serve --host=127.0.0.1 --port=0

With the two seed tickets in place, the first successful POST gets 201 and a ticket with ID 3.

In a second terminal, enter the actual port reported by the running server. These commands connect only to 127.0.0.1.

Run this exercise on a fresh local server with two seed tickets. The first new ticket then receives ID 3. These routes use synthetic data and have no authentication or authorization checks. Keep the server on 127.0.0.1 with no public access, and use the test key only in this demo.

BASH
read -r -p 'Port: ' PORT
BASE_URL="http://127.0.0.1:$PORT"

curl -i -sS --noproxy '*' -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{"title":"  First ticket  ","id":900,"status":"closed"}' "$BASE_URL/api/tickets"

curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets/3"

The excerpts below show HTTP requests and their observed responses. The port and some headers are omitted.

HTTP
POST /api/tickets HTTP/1.1
Host: 127.0.0.1
Accept: application/json
Content-Type: application/json
Content-Length: 55

{"title":"  First ticket  ","id":900,"status":"closed"}

HTTP
HTTP/1.1 201 Created
Content-Type: application/json

{"id":3,"title":"First ticket","status":"open"}

HTTP
GET /api/tickets/3 HTTP/1.1
Host: 127.0.0.1
Accept: application/json

HTTP
HTTP/1.1 200 OK
Content-Type: application/json

{"id":3,"title":"First ticket","status":"open"}

For the concurrency exercise, stop and restart the server, then enter its new port in the second terminal. Three requests create tickets with status 201 and one returns 422. After wait, the list contains the seed tickets and new IDs 3–5 with no gaps. The requests may finish in any order.

BASH
read -r -p 'Port: ' PORT
BASE_URL="http://127.0.0.1:$PORT"

curl -sS --noproxy '*' -o /dev/null -w 'Ticket A: %{http_code}\n' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{"title":"Batch ticket 2"}' "$BASE_URL/api/tickets" &
curl -sS --noproxy '*' -o /dev/null -w 'Ticket B: %{http_code}\n' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{"title":"Batch ticket 5"}' "$BASE_URL/api/tickets" &
curl -sS --noproxy '*' -o /dev/null -w 'Ticket C: %{http_code}\n' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{"title":"Batch ticket 8"}' "$BASE_URL/api/tickets" &
curl -sS --noproxy '*' -o /dev/null -w 'Invalid: %{http_code}\n' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{}' "$BASE_URL/api/tickets" &
wait

curl -i -sS --noproxy '*' -H 'Accept: application/json' "$BASE_URL/api/tickets"

In a separate 24-request test, eight inserts received IDs 4–11, eight requests were rejected, and eight read the list. Each read saw all inserts completed before it acquired the lock. Once the store was full, a rejected insert left the existing 32 records intact. Unit tests covered ID exhaustion, mutex poisoning, and the independence of a previously returned copy.

Summary

An application instance shares one store across its handlers. After restarting, only the two seed tickets remain. Separate processes have separate memory. When tickets must survive a restart or be shared across processes, the next step is a data store with atomic inserts and an ID uniqueness constraint.

References