HTTP API: Explicit Contracts · 25 min · free lesson

Validate Before Applying Effects

Check declared and actual request size.

Core idea

A body-length mismatch is a framing error; an exceeded limit is a resource error.

Diagram for Validate Before Applying Effects: a Rust code example flows to the lesson rule and the key observation.
The worked implementation exercises check declared and actual request size. Its tests demonstrate the stated finite contract.

Understand it

A request can advertise one size and deliver another. A server needs limits on both the declared size and accumulated bytes. Check limits before parsing the domain object or applying writes, otherwise an oversized request can consume unbounded resources or leave partial state.

This function receives an optional parsed Content-Length, actual byte count and maximum. Return 413 if either known size exceeds the maximum. Otherwise a present length that differs from actual input returns 400; valid bounded input returns 200. Missing length is accepted by this isolated policy when transport framing has already supplied a complete body. The native HTTP adapter has a stricter framing profile: it rejects chunked transfer, duplicate lengths and pipelined bytes. Never use this size-only policy as a complete HTTP parser.

The route project is Task Ledger: first keep a reproducible source history, then expose its data through a CLI and HTTP boundary, persist it in SQL, diagnose failures and prepare a release. This lesson owns one contract in that project. Run the worked example before changing the starter and explain which input makes the tempting shortcut fail.

Terminal practice: Use curl -i -H "Content-Type: application/json" -d @request.json http://127.0.0.1:8080/tasks and compare a rejected oversized title with a valid request.

The compiler lab is independent of the reading question. Edit solution.rs; the app supplies a separate caller with normal, empty and adversarial inputs. A successful unchanged demonstration does not prove your implementation. After the lab, apply the same contract to the route companion project. Its README separates the on-device adapter from the desktop Cargo/TCP profile.

Read the code

pub fn body_status(
    declared: Option<usize>,
    actual: usize,
    maximum: usize,
) -> u16 {
    if actual > maximum || declared.is_some_and(|n| n > maximum) {
        413
    } else if declared.is_some_and(|n| n != actual) {
        400
    } else {
        200
    }
}

fn main() {
    assert_eq!(body_status(Some(5), 5, 10), 200, "case 1");
    assert_eq!(body_status(Some(0), 0, 0), 200, "case 2");
    assert_eq!(body_status(Some(20), 0, 10), 413, "case 3");
    assert_eq!(body_status(Some(5), 4, 10), 400, "case 4");
    assert_eq!(body_status(None, 11, 10), 413, "case 5");
    assert_eq!(body_status(None, 5, 10), 200, "case 6");
    println!("worked example passed");
}

The worked implementation exercises check declared and actual request size. Its tests demonstrate the stated finite contract.

Practice starter

pub fn body_status(declared: Option<usize>, actual: usize, maximum: usize) -> u16 {
    todo!("implement the contract")
}

Open local example in Playground ↗

Try it

Return 413 if declared or actual bytes exceed maximum; otherwise 400 for a present mismatching length; otherwise 200. Keep the public signature. Open the compiler lab and edit solution.rs; do not edit the private verification caller.

What success looks like: The separate caller accepts the changed solution and rejects unchanged TODO, a wrong implementation and a printed success message.

Check your understanding

Can a small declared length replace a limit on actual bytes?

Reveal the answer
  1. Only decoded character count matters
  2. No, actual bytes also need a bound
  3. Yes, clients always report an accurate size

Clients can lie or disconnect mid-body, so declared size alone is insufficient.

Go deeper

Common misconception: Yes, clients always report an accurate size

A body-length mismatch is a framing error; an exceeded limit is a resource error.

  1. Identify the boundary: Check declared and actual request size. Write down its accepted inputs and observable output.
  2. Exercise the failure: Clients can lie or disconnect mid-body, so declared size alone is insufficient.
  3. Check the independent caller: Return 413 if declared or actual bytes exceed maximum; otherwise 400 for a present mismatching length; otherwise 200.

Transfer challenge: Apply this contract to Task Ledger, introduce the failure described in the lesson, and show the failing check before fixing it.

Connections

  • Route Method and Path Together: Separate unknown routes from disallowed methods
  • Encode a Valid JSON Boundary: Escape JSON strings without corrupting Unicode