How to Implement the Middleware Pattern in Rust

Implement the middleware pattern in Rust by using Atomic types to cache connections to services like the DNS Resolver or Network Server.

Implement the middleware pattern by defining a Connection handler that intercepts requests via connect and routes them through specific service names like "DNS Resolver Middleware" or "Middleware Network Server". Use AtomicU32 to cache the connection ID and ensure thread-safe lazy initialization.

use core::sync::atomic::{AtomicU32, Ordering};
use crate::os::xous::ffi::Connection;
use crate::os::xous::services::connect;

pub(crate) fn dns_server() -> Connection {
    static DNS_CONNECTION: AtomicU32 = AtomicU32::new(0);
    let cid = DNS_CONNECTION.load(Ordering::Relaxed);
    if cid != 0 {
        return cid.into();
    }
    let cid = connect("_DNS Resolver Middleware_").unwrap();
    DNS_CONNECTION.store(cid.into(), Ordering::Relaxed);
    cid
}