Full-stack Rust

Day 6

Rust for bioinformaticians

Visualising biological data — why we’re building a web app

The most useful tool you can give a biologist colleague is one they don’t have to install. A web page in a browser is exactly that: paste a sequence, see GC content, click to load a sample, no setup.

Today we build one — entirely in Rust, frontend and backend.

Frontend, backend, full-stack — the words

These three words come up constantly. They name the parts of every web app you’ve ever used. Today we go full-stack, in Rust, end to end.

What each word actually means

  • Frontend [the code that runs in the user’s browser — HTML + JS, or in our case Rust compiled to WASM (WebAssembly, a binary format browsers can execute)]
  • Backend [the code that runs on a server — receives requests, talks to databases, sends responses; ours is axum]
  • Full-stack [writing both ends]

What today is about

  • A web app written entirely in Rust — frontend, backend, shared types
  • Frontend compiled to WebAssembly, runs in the browser

The shape of the day

  • One workspace with three crates: shared, frontend, backend
  • frontend builds to .wasm, served by trunk [a build tool and dev server for Rust web frontends — like webpack for Yew, with hot reload (auto-rebuild + browser refresh on save) built in]
  • backend builds native, serves /api/samples
  • Both crates depend on shared — same Rust types on the wire
  • After class you are clicking a button, fetching a sequence, plotting GC content over a sliding window
A horizontal flow with four stages — Foundations (HTML, HTTP, JSON, ports), Backend (axum), Frontend (Yew, WASM), Integration (browser fetches from backend) — labelled with which exercise covers each.

Today: foundations (HTML, HTTP, JSON, ports) → axum backend → Yew frontend compiled to WASM → integrated app.

This is what we’re building

Mockup of the reactive sequence inspector UI: sample picker buttons at the top, a textarea showing the loaded DNA sequence, a stats panel showing length and GC content, and an inline SVG plot of GC content along a sliding window.

A mockup of the capstone: pick a sample, see the sequence, live GC stats, and an inline SVG plot.

Before you start — tooling checklist

  • rustup target add wasm32-unknown-unknown [one-time; teaches rustc (the Rust compiler) to emit WASM]
  • cargo install trunk [one-time; trunk is the build tool that runs the Yew dev server]
  • curl or HTTPie installed [for sanity-checking the backend from the command line]
  • Two terminals ready [one for the backend, one for trunk]

Before we touch Rust: three things to know

Most browser-based code rests on three building blocks. None of them is Rust-specific:

  1. HTML — how a page is structured.
  2. HTTP — how the browser talks to a server.
  3. JSON — how structured data moves between the two.

Plus one more cross-cutting concept: ports.

HTML — a page is a tree of boxes

HTML is just text marked up with tags. The browser turns those tags into nested boxes on the screen.

<!-- HTML -->
<html>
  <body>
    <h1>Sequence inspector</h1>
    <p>Paste DNA below:</p>
    <div>
      <textarea></textarea>
      <p>GC content: 50%</p>
    </div>
  </body>
</html>

The <div> is the workhorse: a generic box that can contain other boxes. Almost every interactive component you’ve seen on the web is a <div> (or a few <div>s) with style and code attached.

Side-by-side comparison: HTML source on the left and the rendered nested-boxes layout on the right.

Same HTML, two views: the source on the left, the rendered page on the right.

The DOM — the in-memory tree the browser builds

When the browser parses your HTML, it builds an in-memory tree of nodes called the DOM (Document Object Model). Every box in the rendered page is a node in this tree. Everything that changes the page after load — JavaScript, jQuery, React, Yew — does so by manipulating the DOM tree.

A tree diagram showing html as the root with body, h1, p, and div nodes as children, mirroring the HTML source.

The DOM tree mirrors the HTML structure.
<html>
  <body>
    <h1>Sequence inspector</h1>
    <div>
      <textarea></textarea>
      <p>GC content: 50%</p>
    </div>
  </body>
</html>

HTTP — how the browser talks to a server

When you click a link, the browser sends an HTTP request to a server somewhere. The server sends back an HTTP response.

A request has:

  • a method (GET, POST, …),
  • a URL (https://api.example.com/samples/42),
  • optional headers (auth, content type, …),
  • optional body (for POST / PUT).

A response has:

  • a status code (200 OK, 404 Not Found, …),
  • headers,
  • a body (HTML, JSON, an image, anything).
A browser on the left and a server on the right with arrows showing an HTTP request going out and a response coming back.

An HTTP request goes out; a response comes back.

Ports — finding the right service on a machine

A single computer can run many services at once: a web server, a database, an SSH daemon, your dev backend. To direct traffic to the right one, every service listens on a port — a number from 0 to 65535.

The browser combines IP + port to reach a service:

http://127.0.0.1:3000/api/samples/42
       ───────────  ─── ──────────────
       host         port   path

Common ports: 80 HTTP, 443 HTTPS, 22 SSH, 5432 PostgreSQL. Dev backends usually pick something high like 3000, 8000, or 8080 so they don’t clash with real services.

A single machine box with multiple numbered ports on its edge, a client connecting to one specific port number.

One machine, many ports, one client connecting to one of them.

JSON — how structured data crosses the wire

HTTP bodies are bytes. When you want to send structured data — a list of samples, a record with named fields — the most common encoding is JSON (JavaScript Object Notation).

A JSON record on the wire:

{
  "id": 42,
  "name": "K-12 MG1655",
  "species": "Escherichia coli",
  "sequence": "ACGTACGT..."
}

JSON has just six types: object, array, string, number, boolean, null. Almost every language can read and write it. That’s why the web settled on it.

JSON ↔︎ Rust struct (serde, preview)

serde is the Rust crate that converts back and forth between JSON and your structs — both directions, automatically, from one #[derive]:

// Rust
#[derive(Serialize, Deserialize)]
struct SampleRecord {
    id: u32,
    name: String,
    species: String,
    sequence: String,
}
A JSON object on the left and a Rust struct on the right, with arrows mapping each JSON key to its corresponding struct field.

JSON keys map to Rust struct fields; serde derives both directions from the struct definition.

serde_json::to_string(&record) → JSON. serde_json::from_str(&body) → SampleRecord.

Same struct, both sides of the network call.

async/await — the minimum you need

An async fn [a function that does not block; it returns immediately] returns a Future [a description of work to be done later, not the result itself].

// Rust
async fn fetch_one() -> Result<SampleRecord, gloo_net::Error> {
    let resp = Request::get("/api/samples/lambda").send().await?;
    let data = resp.json::<SampleRecord>().await?;
    Ok(data)
}

.await [the operator that waits for a future to be ready] means: pause this task until the future is ready, let the runtime [the scheduler that decides which task runs when] do other work in the meantime.

We do not teach Future internals today — treat it as a single pattern.

What .await actually does

Sequence diagram with two lifelines: your async code (blue) on the left and browser runtime (yellow) on the right. The code is let resp = Request::get(url).send().await?;. Step 1: solid arrow from your code to browser runtime labelled .send() returns a Future, hand it to the runtime. Step 2: a yellow note on the left labelled .await pauses, this task yields. Step 3: the runtime is shown as active for a long span, annotated runtime is free to run other tasks (rendering, other awaits, animations). Step 4: a small self-call on the runtime lifeline labelled network response arrives. Step 5: dashed return arrow from runtime to your code labelled runtime polls the future, sees it is ready, resumes your task. Step 6: a green note labelled resp bound, next statement runs. A time arrow runs top to bottom. Footer: No threads, no blocking — the function pauses at .await and resumes when the work is done.

.await yields; the runtime resumes you when the work is done.

A REST server in 20 lines of axum

REST [HTTP verbs + URL paths to access named resources]. axum [a Rust web framework for HTTP servers] is the backend library we use today. The smallest possible backend — accepts a DNA sequence, returns its GC content:

use axum::{routing::get, Router, extract::Query};
use serde::{Serialize, Deserialize};

#[derive(Deserialize)] struct GcQuery { seq: String }
#[derive(Serialize)]   struct GcAnswer { length: usize, gc: f64 }

async fn gc(Query(q): Query<GcQuery>) -> axum::Json<GcAnswer> {
    let n = q.seq.len();
    let g = q.seq.bytes().filter(|b| matches!(b, b'G' | b'C')).count();
    axum::Json(GcAnswer { length: n, gc: g as f64 / n.max(1) as f64 })
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/gc", get(gc));
    let l = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(l, app).await.unwrap();
}

REST server — the call flow

A flow diagram showing a client sending GET /gc?seq=ACGT to axum, the router dispatching to the gc handler, and a JSON response being returned.

The flow: client requests GET /gc?seq=ACGT → axum routes → gc() handler → JSON response.

Calling it with curl

You can hit any REST endpoint from the command line — no browser needed:

# bash
$ curl 'http://127.0.0.1:3000/gc?seq=ACGTACGTGGGG'
{"length":12,"gc":0.6666666666666666}

curl is your sanity check: does the backend work? Yes? Then add the frontend.

WebAssembly: a binary the browser can run

WebAssembly (or WASM) [a portable, sandboxed (isolated execution environment) binary format that every modern browser can load and execute] is just that: a compiled binary the browser knows how to run.

A diagram of the WebAssembly build flow: Rust source compiled by rustc into a .wasm binary, then loaded and executed by the browser.

Rust source compiled to a .wasm binary the browser loads.

Why it matters for us

  • Rust → .wasm → browser, with near-native performance
  • A compile target, not a language — Rust, C, C++, Go can all produce .wasm
  • We write Rust today, change the build target, get a .wasm file the browser runs
  • No JavaScript runtime cost on the hot path

The build pipeline — step 1: Rust source

Step 1 of the build pipeline: Rust source files (main.rs, lib.rs, Cargo.toml) shown as the starting point.

Step 1: your Rust source.

The build pipeline — step 2: cargo + wasm-bindgen

Step 2 of the build pipeline: cargo compiles Rust source to a .wasm binary and wasm-bindgen emits accompanying JavaScript glue.

Step 2: cargo compiles to a .wasm; wasm-bindgen generates JS glue.

The build pipeline — step 3: trunk bundles

Step 3 of the build pipeline: trunk bundles the .wasm, JS glue, index.html and assets into a /dist directory served to the browser.

Step 3: trunk bundles everything into a /dist directory the browser loads.

wasm32-unknown-unknown

# bash
rustup target add wasm32-unknown-unknown

Rust target triples are arch-vendor-os:

  • wasm32 — 32-bit WebAssembly instruction set
  • unknown — no specific vendor
  • unknown — no specific OS (it is just a VM)

cargo build --target wasm32-unknown-unknown invokes rustc with that target. Output is target/wasm32-unknown-unknown/debug/your_crate.wasm.

wasm-bindgen — the JS glue layer

Pure WebAssembly only speaks integers and floats. It cannot return a String to JavaScript, and it cannot touch the DOM directly.

wasm-bindgen generates a tiny JavaScript shim that:

  • marshals strings, structs, closures across the JS↔︎WASM boundary
  • exposes browser APIs (DOM, fetch, setTimeout) to your Rust code
  • lets you #[wasm_bindgen] a Rust function and call it from JS

wasm-bindgen is the bridge: it lets your Rust code in the .wasm file read and modify the DOM that the browser built from your HTML.

You will rarely touch it directly — Yew and gloo_net use it under the hood.

Trunk — build tool for Yew apps

Trunk is cargo build for web frontends:

# bash
cargo install trunk      # one-off
trunk serve              # in the frontend/ directory

In one command, trunk:

  1. compiles your frontend crate to wasm (cargo build --target wasm32-...)
  2. runs wasm-bindgen to generate the JS glue
  3. bundles index.html, .wasm, .js, assets into dist/
  4. serves dist/ over HTTP on :8080
  5. watches your source files and rebuilds + reloads the browser on save

A Cargo workspace — three crates in one tree

Two-panel diagram. Left panel: directory tree with sequence-inspector/ at the root containing Cargo.toml (workspace root), Cargo.lock, shared/ (Cargo.toml, src/lib.rs — SampleRecord), frontend/ (Cargo.toml, Trunk.toml, index.html, src/main.rs — Yew app), backend/ (Cargo.toml, src/main.rs — axum server), and target/ noted as one shared build dir. Right panel: dependency graph showing frontend (blue, compiles to WASM) and backend (green, compiles native) each with an arrow labelled uses pointing down to shared (yellow), which contains SampleRecord and SampleSummary serde-derived types. Footer: One Rust type, two compile targets. The same struct validates both sides of the network call — no schema drift between client and server.

One Rust type, two compile targets, zero schema drift.

What the workspace Cargo.toml looks like

# TOML — root Cargo.toml
[workspace]
resolver = "2"
members = ["shared", "frontend", "backend"]

[workspace.dependencies]
shared = { path = "shared" }
serde  = { version = "1", features = ["derive"] }

Each member crate references shared and serde with one line:

# TOML — member Cargo.toml
shared.workspace = true
serde.workspace  = true

The shared-types pattern

// shared/src/lib.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SampleRecord {
    pub id: String,
    pub name: String,
    pub sequence: String,
}

Both frontend and backend depend on shared. The same struct is serialised by the server and deserialised by the client.

Yew — Rust UI framework

Yew is modelled on React [the dominant JavaScript UI library — Yew works similarly].

  • Components are functions that return Html
  • State lives in hooks [reusable functions starting with use_ that hold per-component state across re-renders] like use_state, use_effect_with
  • The framework re-runs the function on every state change
// Rust
use yew::prelude::*;

#[function_component(App)]
fn app() -> Html {
    let title = "Sequence inspector";
    let length = 42;
    html! {
        <div>
            <h1>{ title }</h1>
            <p>{ format!("Loaded {} bases", length) }</p>
        </div>
    }
}

Yew renders a <div> containing an <h1> and a <p>. Inside { ... } you put any Rust expression.

The render loop

Each render Yew builds a virtual DOM [an in-memory tree of the HTML you want, cheaper to construct and compare than the real browser DOM], then performs a diff/patch [compare the new vDOM to the previous one and apply only the minimal real-DOM changes] step.

Four-step flow. Yellow state box (typed: String, held in use_state, survives rerenders) arrows into blue component fn box (fn app() -> Html, returns a virtual DOM, a tree of Html nodes) arrows into blue diff box (new vDOM vs previous vDOM, finds minimum change) arrows into green patch box (real DOM nodes update, minimal changes only). An orange curved arrow loops from patch back to state, labelled: event handler calls handle.set(new_value) (oninput, onclick, ...). State changes triggers Yew to re-run the function and the cycle repeats. Footer: Same model as React. Components are functions. State lives in hooks. Render returns a virtual DOM. The framework diffs and patches — you describe what the page should look like, not how to update it.

You describe the page; state changes drive the rerender.

The html! macro

// Rust — html!{} looks like HTML but is parsed as Rust tokens
html! {
    <div>
        <h1>{ "Sequence inspector" }</h1>
        <p>{ format!("length: {} bp", seq.len()) }</p>
    </div>
}

HTML-shaped syntax in Rust source. { ... } slots embed any Rust expression.

Differences from plain HTML:

  • Every tag must be closed (<br/>, not <br>)
  • Text goes inside { }: <p>{ "hi" }</p>
  • Multiple top-level elements: wrap in <></>

#[function_component(App)]

// Rust
#[function_component(App)]
fn app() -> Html {
    let sequence = use_state(String::new);
    let dna: &str = &sequence;
    html! { <p>{ dna }</p> }
}

fn main() {
    yew::Renderer::<App>::new().render();
}

The attribute turns a plain fn into a Component named App. main mounts it.

Closures and move — 30 seconds

A closure [an inline anonymous function that captures variables from its enclosing scope] looks like |x| x + 1. move [keyword that makes the closure take ownership of its captured variables] is needed when the closure outlives the scope — for example when an event handler runs later, after the surrounding function has returned.

// Rust
let name = String::from("lambda");
let say_hi = move |_| log::info!("hello, {name}");  // owns `name`
// `say_hi` can now be stored in a Callback and called from an event

Event handlers in Yew are stored in the framework and called later — so the closures we hand them are almost always move closures.

use_state — a value that survives re-renders

Diagram of use_state. A code panel inside #[function_component(App)] shows let length = use_state(|| 0_usize); (closure called once on first render), let n: usize = *length; (read) and length.set(sequence.len()); (write — triggers rerender). A click handler reads Callback::from(move |_| { length.set(sequence.len()); }). The handle is the same on every render; only the value behind it changes.

The handle is stable across renders; only its value changes.

// Rust
let length = use_state(|| 0_usize);

let on_click = {
    let length = length.clone();
    let sequence = sequence.clone();
    Callback::from(move |_| length.set(sequence.len()))
};

Callback::from(...) wraps a closure into a Yew callback [a closure stored by the framework, invoked when a DOM event (click, input, …) fires].

Controlled input — input bound to state

A controlled input [displayed value reads from state; changes write back] makes the Rust value the single source of truth.

let typed = use_state(String::new);

let on_input = {
    let typed = typed.clone();
    Callback::from(move |e: InputEvent| {
        let target = e.target_unchecked_into::<web_sys::HtmlInputElement>();
        typed.set(target.value());
    })
};

html! {
    <input type="text" value={(*typed).clone()} oninput={on_input} />
}

State is the input’s value. Keystroke writes; the value attribute reads.

use_effect_with — run something when deps change

// Rust
use_effect_with((), move |_| {
    // body runs once on mount, because deps = ()
    log::info!("sequence inspector mounted");
    || ()    // cleanup closure; () == "nothing to clean up"
});
  • deps = () → run once, on first render
  • deps = some_state.clone() → run again whenever that state changes
  • The body returns a cleanup closure (for unsubscribing, cancelling timers, etc.)

spawn_local — run an async block on the event loop

// Rust
use wasm_bindgen_futures::spawn_local;

spawn_local(async move {
    let resp = Request::get("/api/samples").send().await.unwrap();
    let data: Vec<SampleSummary> = resp.json().await.unwrap();
    samples.set(data);
});

spawn_local [the function that schedules an async block on the browser’s single-threaded event loop] hands an async block to the browser’s event loop. From there it runs cooperatively, just like a JS promise.

Loading samples on mount

{
    let samples = samples.clone();
    use_effect_with((), move |_| {
        spawn_local(async move {
            if let Ok(resp) = Request::get("/api/samples").send().await {
                if let Ok(data) = resp.json::<Vec<SampleSummary>>().await {
                    samples.set(data);
                }
            }
        });
        || ()
    });
}

use_effect_with((), …) runs once on mount; spawn_local runs the async fetch.

gloo_net::Request — fetch from WASM

// Rust
use gloo_net::http::Request;

let resp = Request::get("/api/samples").send().await?;
let data: Vec<SampleSummary> = resp.json().await?;

Two awaits:

  • one for the response headers and status
  • one for the body, fully received and decoded by serde

gloo_net wraps the browser’s native fetch() API in a typed Rust interface.

axum — Rust HTTP server

use axum::{routing::get, Json, Router};
use shared::SampleSummary;

async fn list_samples() -> Json<Vec<SampleSummary>> {
    Json(vec![/* ... */])
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let app = Router::new().route("/api/samples", get(list_samples));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await
}

A route maps URL+method to a handler — an async fn returning something serialisable. See axum.

Path parameters and JSON bodies

// Rust
use axum::extract::Path;

async fn get_sample(Path(id): Path<String>) -> Json<SampleRecord> {
    let record = lookup_sample(&id);   // your code
    Json(record)
}

let app = Router::new()
    .route("/api/samples", get(list_samples))
    .route("/api/samples/{id}", get(get_sample));

Path<T> is an extractor [a typed argument in a handler signature that tells axum what to pull out of the incoming request — the URL path, a query string, a JSON body, headers, …] — axum parses the URL segment for you and hands you the typed value.

CORS — and why we usually avoid it

An origin [scheme + host + port] is the browser’s unit of trust. :8080 and :3000 are different origins.

The Same-Origin Policy blocks fetch from one origin to another unless the server opts in with CORS [Cross-Origin Resource Sharing headers].

Two ways to handle it:

  • Enable CORS on axum with tower_http::cors::CorsLayer::permissive() (real apps)
  • Proxy through trunk — trunk forwards /api/... to axum, browser sees one origin (today)

The trunk dev proxy

# TOML — frontend/Trunk.toml
[[proxy]]
rewrite = "/api/"
backend = "http://127.0.0.1:3000/api/"

Now fetch('/api/samples') from the browser goes to trunk on :8080, which forwards it to axum on :3000.

The browser sees one origin. CORS never comes up. Production deploys still need real CORS (or same-origin hosting).

Putting it together — one click

  1. User clicks a sample button
  2. on_pick runs, calls spawn_local
  3. gloo_net::Request::get("/api/samples/lambda").send().await
  4. Trunk forwards to axum on :3000
  5. axum extracts the path, returns Json(record) — serde encodes
  6. Body arrives in the browser, resp.json().await — serde decodes (same struct)
  7. Frontend writes the sequence into typed state — Yew rerenders
  8. Stats and the SVG plot update for free

What we deliberately skip

In scope: function components, use_state, use_effect_with, Callback::from, one async fn pattern, spawn_local, gloo_net::Request, serde, axum routes + handlers, trunk + dev proxy, inline SVG in html!.

Out of scope: Future internals, pinning, executors; axum state and middleware; full Yew agents/lifecycle/portals; wasm-bindgen deep magic.

The app is structurally identical to a real Rust web app. The “out” items will not stop you shipping.

To the exercises

  • Exercise 1 — get the toolchain alive: trunk serves a Yew page, you make a change, the browser reloads
  • Exercise 2 — reactive stats: textarea + use_state + GC content live on every keystroke
  • Exercise 3 — fetch samples from axum via gloo_net
  • Exercise 4 (capstone) — inline SVG plot of GC sliding window

Two terminals open. cargo run -p backend in one, trunk serve in frontend/ in the other.