Enum Queries Carry Reply Channels

Bundle a one-shot reply Sender into each enum query so the requestor blocks on a typed answer while the server thread dispatches with match.

RustResilience

Code

rustsnippet
41 lines
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;

// 每条消息自带一个一次性应答通道:请求方等待具体答复
enum Query {
    Lookup { key: String, reply: Sender<Option<u32>> },
    Count { reply: Sender<usize> },
}

fn serve(store: Vec<(String, u32)>, queries: Receiver<Query>) {
    for query in queries {
        match query {
            Query::Lookup { key, reply } => {
                let found = store.iter().find(|(name, _)| *name == key).map(|(_, id)| *id);
                let _ = reply.send(found);
            }
            Query::Count { reply } => {
                let _ = reply.send(store.len());
            }
        }
    }
}

fn main() {
    let store = vec![("billing".to_string(), 101), ("auth".to_string(), 202)];
    let (tx, rx) = channel::<Query>();
    thread::spawn(move || serve(store, rx));

    // Lookup 的应答类型是 Option<u32>
    let (id_tx, id_rx) = channel::<Option<u32>>();
    tx.send(Query::Lookup { key: "auth".into(), reply: id_tx.clone() }).unwrap();
    println!("lookup: {:?}", id_rx.recv().unwrap());

    tx.send(Query::Lookup { key: "missing".into(), reply: id_tx }).unwrap();
    println!("missing: {:?}", id_rx.recv().unwrap());

    // Count 的应答类型不同:单独一条应答通道
    let (count_tx, count_rx) = channel::<usize>();
    tx.send(Query::Count { reply: count_tx }).unwrap();
    println!("count: {}", count_rx.recv().unwrap());
}

Tracing from input to output

Structurally, expect the functions serve and main and nothing else.

One loop does the cycling here: for query in queries. match here is the control flow: arms enumerate the value’s shapes exhaustively.

What to watch for

  • All of its behavior originates in the standard library, so no external surface exists.

Applying it

Entry signature: fn serve(store: Vec<(String, u32)

The run prints lookup:, missing:, count: — each prefix names the step that produced it.

Running the file executes main, which drives serve in order.

Statements that matter

let found = store.iter().find(|(name, _)| *name == key).map(|(_, id)| *id);
tx.send(Query::Lookup { key: "auth".into(), reply: id_tx.clone() }).unwrap();
tx.send(Query::Lookup { key: "missing".into(), reply: id_tx }).unwrap();

Interactive Tools for This Topic

FAQ

What does Enum Queries Carry Reply Channels print when run?
Execute the whole file; each printed line is prefixed with a label like `lookup:`, `missing:`, `count:`.