requisite 0.1.0

Data-handling requirements encoded in Rust types.
Documentation
//! Payment and alerting flow with typed trust, freshness, and confidence.
//!
//! The request field passes through a sanitizer before lookup. The market quote
//! carries a TTL and is checked before charging. The forecast passes through a
//! confidence gate that authorizes the matching alert level.
//!
//! Run with: `cargo run --example payment_flow`

use requisite::fresh::scoped::with_live;
use requisite::prelude::*;
use requisite::trust::sanitize;
use std::time::Duration;

// --- domain types -----------------------------------------------------------

#[derive(Debug, Clone, Copy)]
struct Money {
    cents: u64,
}

#[derive(Debug)]
struct Sku(#[allow(dead_code)] &'static str);

// --- where data comes in (each one tags the value at the edge) --------------

/// Mark a simulated HTTP field as untrusted input.
fn read_body_field(raw: &str) -> Tainted<String, Untrusted> {
    Tainted::from_input(raw.to_string())
}

/// Fetch a simulated market price with a TTL.
fn fetch_quote(_sku: &Sku, ttl: Duration) -> Fresh<Money> {
    Fresh::fetch(Money { cents: 4_99 }, ttl)
}

/// Attach confidence to a simulated aurora forecast.
fn aurora_tonight(kp_index: f64) -> Confident<bool> {
    // crude: confidence rises with how far over the kp=5 threshold we are
    let over = (kp_index - 5.0).max(0.0);
    Confident::new(kp_index > 5.0, (0.5 + over * 0.2).min(0.99))
        .expect("the forecast formula produces a valid probability")
}

// --- typed operations -------------------------------------------------------

fn db_lookup_customer(id: Tainted<String, Trusted>) -> String {
    // The parameter requires an ID that passed through `sanitize`.
    format!("customer<{}>", id.into_inner())
}

fn charge(customer: &str, amount: Money) {
    println!("  charged {} cents to {customer}", amount.cents);
}

fn wake_slepp(_proof: Certain, reason: &str) {
    // The parameter requires authorization from the highest confidence tier.
    println!("  *** WAKING SLEPP: {reason} ***");
}

fn buzz_phone(reason: &str) {
    println!("  (silent buzz) {reason}");
}

// --- the flow ---------------------------------------------------------------

fn main() {
    println!("== trust ==");
    let raw_id = read_body_field("42; DROP TABLE customers");
    println!("  raw input: {:?}", raw_id.as_ref());
    let safe_id = sanitize(raw_id, |s| {
        s.chars().filter(|c| c.is_ascii_digit()).collect()
    });
    let customer = db_lookup_customer(safe_id);
    println!("  resolved {customer}");

    println!("== freshness (runtime TTL) ==");
    let quote = fetch_quote(&Sku("WIDGET"), Duration::from_millis(50));
    match quote.get() {
        Ok(price) => {
            charge(&customer, *price);
            println!("  ({:?} of freshness left)", quote.remaining());
        }
        Err(stale) => println!("  refused: {stale}"),
    }

    println!("== freshness (scope escape, static) ==");
    // Return an owned result derived during this scoped operation.
    let total = with_live(Money { cents: 999 }, |live| {
        let p = live.get();
        p.cents + 1
    });
    println!("  derived {total} during the live value's scope");

    println!("== confidence gating (proof token) ==");
    for kp in [3.0_f64, 5.4, 8.5] {
        let aurora = aurora_tonight(kp);
        let conf = aurora.confidence();
        let outcome = match aurora.gate() {
            Gate::HighConfidence(proof, _is) => {
                wake_slepp(proof, "strong aurora");
                "woke"
            }
            Gate::Likely(_is) => {
                buzz_phone("maybe aurora");
                "buzzed"
            }
            Gate::Unsure(_is) => "logged",
        };
        println!("  kp={kp} conf={conf:.2} -> {outcome}");
    }
}