Course › Week 4 · Async and plugging into Laravel › Day 7 · lesson 28 of 42 · 30 min reading + 1–2 h practice
Week 4 checkpoint
Kill the database mid-run: Laravel gets a clear error and no half-written batch.
On this page
Five problems, all of them the kind a worker meets in production. Problem 1 is the one this week’s design exists for: the database fails in the middle of saving a batch. Each program here runs against the real Postgres, where a trigger makes the third update fail as a full disk would.
As before: decide what is wrong and why before you open the answer.
1. The database fails halfway through a save
Three results to save. The third update fails. This version saves each result on its own:
use std::env;
use std::error::Error;
use sqlx::PgPool;
const RESULTS: [(i64, i32); 3] = [(1042, 43), (1043, 30), (1045, 50)];
async fn save(pool: &PgPool) -> Result<(), sqlx::Error> {
for (id, tenths) in RESULTS {
sqlx::query(
"update evaluations set status = 'analysed', average_tenths = $2 where id = $1",
)
.bind(id)
.bind(tenths)
.execute(pool)
.await?;
}
Ok(())
}
/// What a Laravel dashboard would show afterwards.
async fn print_statuses(pool: &PgPool) -> Result<(), sqlx::Error> {
let rows: Vec<(i64, String)> = sqlx::query_as("select id, status from evaluations order by id")
.fetch_all(pool)
.await?;
for (id, status) in rows {
println!(" #{id}: {status}");
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
if let Err(error) = save(&pool).await {
println!("save failed: {error}");
}
print_statuses(&pool).await?;
Ok(())
}
save failed: error returned from database: could not extend file: No space left on device (simulated for evaluation 1045) at line 3897
#1042: analysed
#1043: analysed
#1045: pendingShow the solution
One sentence: each update was committed on its own, so the failure on the third left two evaluations analysed and one pending, and a retry of the batch would analyse and save the first two again.
The fix: one transaction around the whole batch, exactly the worker’s db::save. The failure rolls back the first two updates, and the batch is either entirely saved or entirely retryable.
use std::env;
use std::error::Error;
use sqlx::PgPool;
const RESULTS: [(i64, i32); 3] = [(1042, 43), (1043, 30), (1045, 50)];
async fn save(pool: &PgPool) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
for (id, tenths) in RESULTS {
sqlx::query(
"update evaluations set status = 'analysed', average_tenths = $2 where id = $1",
)
.bind(id)
.bind(tenths)
.execute(&mut *tx)
.await?;
}
tx.commit().await
}
/// What a Laravel dashboard would show afterwards.
async fn print_statuses(pool: &PgPool) -> Result<(), sqlx::Error> {
let rows: Vec<(i64, String)> = sqlx::query_as("select id, status from evaluations order by id")
.fetch_all(pool)
.await?;
for (id, status) in rows {
println!(" #{id}: {status}");
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
if let Err(error) = save(&pool).await {
println!("save failed: {error}");
}
print_statuses(&pool).await?;
Ok(())
}
save failed: error returned from database: could not extend file: No space left on device (simulated for evaluation 1045) at line 3897
#1042: pending
#1043: pending
#1045: pendingSame failure, nothing half-written. This is the proof the week promised: kill the database mid-save, and the worker exits 1 with every evaluation still pending, so the queue’s retry starts from a clean state.
2. A save that never happens
It compiles without a single warning, it prints “saved”, and the database disagrees. Only clippy, run before the program here, says anything:
use std::env;
use std::error::Error;
use sqlx::PgPool;
async fn mark_analysed(pool: &PgPool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("update evaluations set status = 'analysed' where id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(())
}
/// What a Laravel dashboard would show afterwards.
async fn print_statuses(pool: &PgPool) -> Result<(), sqlx::Error> {
let rows: Vec<(i64, String)> = sqlx::query_as("select id, status from evaluations order by id")
.fetch_all(pool)
.await?;
for (id, status) in rows {
println!(" #{id}: {status}");
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
let _ = mark_analysed(&pool, 1042);
println!("saved #1042");
print_statuses(&pool).await?;
Ok(())
}
src/main.rs:29:5: warning: non-binding `let` on a futuresaved #1042
#1042: pending
#1043: pending
#1045: pendingShow the solution
One sentence: an async function only runs when its future is awaited, and let _ = threw the future away, along with any error it would have returned.
The fix: mark_analysed(&pool, 1042).await?;. The async lesson showed the compiler warning about an unused future; let _ = is how you tell the compiler you discard a value on purpose, so it stays quiet. clippy’s let_underscore_future lint still catches it, which is one more reason clippy runs before every commit. Never use let _ = on a future or a Result.
use std::env;
use std::error::Error;
use sqlx::PgPool;
async fn mark_analysed(pool: &PgPool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("update evaluations set status = 'analysed' where id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(())
}
/// What a Laravel dashboard would show afterwards.
async fn print_statuses(pool: &PgPool) -> Result<(), sqlx::Error> {
let rows: Vec<(i64, String)> = sqlx::query_as("select id, status from evaluations order by id")
.fetch_all(pool)
.await?;
for (id, status) in rows {
println!(" #{id}: {status}");
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
mark_analysed(&pool, 1042).await?;
println!("saved #1042");
print_statuses(&pool).await?;
Ok(())
}
saved #1042
#1042: analysed
#1043: pending
#1045: pending3. A task that borrows the pool
use std::env;
use std::error::Error;
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
let count = tokio::spawn(async {
sqlx::query_scalar::<_, i64>("select count(*) from evaluations")
.fetch_one(&pool)
.await
});
println!("{} evaluations", count.await??);
Ok(())
}
error[E0373]: async block may outlive the current function, but it borrows `pool`, which is owned by the current function
--> src/main.rs:10:30
|
10 | let count = tokio::spawn(async {
| ^^^^^ may outlive borrowed value `pool`
11 | sqlx::query_scalar::<_, i64>("select count(*) from evaluations")
12 | .fetch_one(&pool)
| ---- `pool` is borrowed here
|
= note: async blocks are not executed immediately and must either take a reference or ownership of outside variables they use
help: to force the async block to take ownership of `pool` (and any other referenced variables), use the `move` keyword
|
10 | let count = tokio::spawn(async move {
| ++++
For more information about this error, try `rustc --explain E0373`.
error: could not compile `hello` (bin "hello") due to 1 previous errorShow the solution
One sentence: a spawned task may outlive main’s stack frame, so it cannot hold a reference to pool, a local variable.
The fix: give the task its own handle. pool.clone() is cheap (the clones share the same connections) and async move moves it in. The ?? unwraps twice: once for the task (did it panic?), once for the query.
use std::env;
use std::error::Error;
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
let task_pool = pool.clone();
let count = tokio::spawn(async move {
sqlx::query_scalar::<_, i64>("select count(*) from evaluations")
.fetch_one(&task_pool)
.await
});
println!("{} evaluations", count.await??);
Ok(())
}
3 evaluations4. A retryable failure, filed as permanent
The API is overloaded and answers 503. The classification decides whether Laravel tries again later:
use std::time::Duration;
use reqwest::Client;
use serde::Deserialize;
#[derive(Deserialize)]
struct Status {
status: String,
}
/// Returns the status, or (reason, retryable).
async fn check(client: &Client, url: &str) -> Result<String, (String, bool)> {
let response = client
.get(url)
.send()
.await
.map_err(|e| (e.to_string(), e.is_timeout() || e.is_connect()))?;
let body: Status = response
.json()
.await
.map_err(|e| (format!("unexpected body: {e}"), false))?;
Ok(body.status)
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let client = Client::builder().timeout(Duration::from_secs(5)).build()?;
match check(
&client,
"http://127.0.0.1:8000/api/unstable?key=checkpoint-before",
)
.await
{
Ok(status) => println!("ok: {status}"),
Err((reason, retryable)) => println!("failed: {reason} (retryable: {retryable})"),
}
Ok(())
}
failed: unexpected body: error decoding response body for url (http://127.0.0.1:8000/api/unstable?key=checkpoint-before) (retryable: false)Show the solution
One sentence: the 503 was decoded as if it were a success, so a temporary outage turned into “unexpected body”, and an evaluation that would have worked in a minute is reported as never analysable.
The fix: look at the status before the body, as the reqwest lesson said: 429 and 5xx are retryable, other error statuses are not, and only a success is decoded.
use std::time::Duration;
use reqwest::{Client, StatusCode};
use serde::Deserialize;
#[derive(Deserialize)]
struct Status {
status: String,
}
/// Returns the status, or (reason, retryable).
async fn check(client: &Client, url: &str) -> Result<String, (String, bool)> {
let response = client
.get(url)
.send()
.await
.map_err(|e| (e.to_string(), e.is_timeout() || e.is_connect()))?;
let status = response.status();
if !status.is_success() {
let retryable = status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
return Err((format!("answered {status}"), retryable));
}
let body: Status = response
.json()
.await
.map_err(|e| (format!("unexpected body: {e}"), false))?;
Ok(body.status)
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let client = Client::builder().timeout(Duration::from_secs(5)).build()?;
match check(
&client,
"http://127.0.0.1:8000/api/unstable?key=checkpoint-after",
)
.await
{
Ok(status) => println!("ok: {status}"),
Err((reason, retryable)) => println!("failed: {reason} (retryable: {retryable})"),
}
Ok(())
}
failed: answered 503 Service Unavailable (retryable: true)5. One friendly line too many
The worker works when you run it by hand. Laravel’s json_decode fails on every run:
use serde::Serialize;
#[derive(Serialize)]
struct Output {
analysed: Vec<i64>,
}
fn main() {
println!("worker starting, 2 evaluations");
let output = Output {
analysed: vec![1042, 1043],
};
match serde_json::to_string(&output) {
Ok(json) => println!("{json}"),
Err(error) => eprintln!("worker: {error}"),
}
}
worker starting, 2 evaluations
{"analysed":[1042,1043]}Show the solution
One sentence: stdout is the result channel, and a status line printed there makes it two lines, of which only the second is JSON.
The fix: eprintln! for anything meant for people, or a tracing log, which goes to stderr. A CI test that runs the real binary and parses its stdout with json_decode catches this the first time anyone adds a line like it.
use serde::Serialize;
#[derive(Serialize)]
struct Output {
analysed: Vec<i64>,
}
fn main() {
eprintln!("worker starting, 2 evaluations");
let output = Output {
analysed: vec![1042, 1043],
};
match serde_json::to_string(&output) {
Ok(json) => println!("{json}"),
Err(error) => eprintln!("worker: {error}"),
}
}
{"analysed":[1042,1043]}
worker starting, 2 evaluationsOn this page stdout and stderr appear in the same box, stdout first. Laravel receives them separately: output() is now exactly one JSON document.
The worker exit check
Your worker passes when every line here is true:
| Check | How to verify |
|---|---|
| A database failure during the save leaves every evaluation of the batch pending | Add problem 1’s trigger to your local database and run a batch: exit 1, nothing analysed |
| The analysis API down: exit 1, nothing saved | Point ANALYSIS_URL at a closed port |
Evaluations with no answers or unknown ids: exit 3, listed with retryable: false | Include one of each in a job |
| A malformed job: exit 2, nothing touched | echo '{}' | bin/worker |
| stdout is exactly one JSON document in every outcome that has one | Run each case with 2>/dev/null and pipe into jq . |
| No colour codes in stderr | bin/worker < job.json 2>&1 >/dev/null | cat -v shows no ^[[ |
cargo test, cargo clippy --all-targets, cargo fmt --check | All silent except the test report |
The PHP side: Process::fake tests for exit codes 0, 1, 2, 3 and 101 | Run them in your Laravel app |
What PHP would have done
| Problem | PHP | Rust |
|---|---|---|
| 1. A batch saved without a transaction | The same half-written batch | The same: only the design prevents it |
| 2. A call that is never run | Not possible: PHP calls run immediately | Silent for the compiler after let _ =; clippy catches it |
| 3. Background work borrowing a local | A queued closure serialises a copy | Compile error E0373 |
| 4. An error status decoded as success | ->json() on a 503 returns the error body as data | A decode error, misclassified |
| 5. A log line on the result channel | echo before the JSON: the same broken output | The same: a convention, tested in CI |
Three of the five are not about Rust at all. A transaction, a status check and a clean stdout are protocol decisions; Rust only makes sure that what you did decide is applied everywhere.
Remember
- A transaction, a status check and a clean stdout are decisions; Rust only enforces the ones you made.
Week 5 turns the worker into an HTTP service with axum: routes, JSON, shared state, errors as responses, and middleware, called from Laravel with Http::post().