fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! Idempotency keys, as the PHP package's `Idempotency` middleware handles them: a POST, PATCH or
//! DELETE with an `Idempotency-Key` runs once, and retries with the same key get the stored
//! response with `Idempotent-Replayed: true`. A retry must be the same request (the same version,
//! query and body), or it gets a 422 `idempotency_key_mismatch`. While the first request runs,
//! retries get a 409 `idempotency_in_progress`.

use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{HeaderName, HeaderValue, StatusCode};
use laravel::cache::Repository;
use laravel::http::{Request, Response};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::errors::{ApiError, ApiErrorCode};
use crate::{Config, Context};

/// The request header that carries the key.
pub const HEADER: &str = "Idempotency-Key";

/// The response header that marks a replay.
pub const REPLAYED_HEADER: &str = "idempotent-replayed";

/// Headers that belong to one delivery of the response, not to the response itself.
const UNSTORED_HEADERS: [&str; 3] = ["date", "x-request-id", "set-cookie"];

#[derive(Serialize, Deserialize)]
struct Stored {
    fingerprint: String,
    status: u16,
    headers: Vec<(String, String)>,
    body: String,
}

fn sha256(parts: &[&str]) -> String {
    Sha256::digest(parts.join("\n").as_bytes())
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Runs `inner` once per idempotency key. Requests without a key, with another method, or with
/// idempotency off go straight to `inner`.
pub(crate) async fn guard<F, Fut>(
    config: &Config,
    version: &str,
    mut request: Request,
    inner: F,
) -> Result<Response, Box<(ApiError, Request)>>
where
    F: FnOnce(Request) -> Fut,
    Fut: Future<Output = Response>,
{
    let settings = &config.idempotency;
    let method = request.method().as_str().to_owned();
    let key = request.header(HEADER).map(str::to_owned);
    let Some(key) = key.filter(|_| settings.enabled && settings.methods.contains(&method)) else {
        return Ok(inner(request).await);
    };

    if key.is_empty() || key.len() > 255 {
        return Err(Box::new((
            ApiError::new(
                ApiErrorCode::InvalidIdempotencyKey,
                "Use a unique value of up to 255 characters, such as a UUID.",
            )
            .header_source(HEADER),
            request,
        )));
    }

    let store = match store(settings.store.as_deref()) {
        Ok(store) => store,
        Err(error) => return Ok(Response::new(error)),
    };
    let scope = request
        .extension::<Context>()
        .and_then(|context| context.client.as_ref())
        .map_or_else(
            || "guest".to_owned(),
            |client| format!("client:{}", client.idempotency_scope),
        );
    let path = request.path().trim_start_matches('/').to_owned();
    let store_key = format!(
        "fusion-stack:idempotency:{}",
        sha256(&[&scope, &method, &path, &key])
    );
    // The body as the client sent it, as PHP's getContent() reads it.
    if let Err(error) = request.load_input().await {
        return Ok(Response::new(error));
    }
    let body = request
        .content()
        .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
        .unwrap_or_default();
    let fingerprint = sha256(&[version, request.uri().query().unwrap_or_default(), &body]);

    if let Ok(Some(stored)) = store.get::<Stored>(&store_key).await {
        return replay(stored, &fingerprint, request);
    }

    let lock = store.lock(
        &store_key.replacen("idempotency:", "idempotency-lock:", 1),
        Duration::from_secs(settings.lock_seconds),
    );
    if !lock.acquire().await.unwrap_or(false) {
        return Err(Box::new((
            ApiError::new(
                ApiErrorCode::IdempotencyInProgress,
                "A request with this Idempotency-Key is still running. Retry when it has finished.",
            )
            .header_source(HEADER),
            request,
        )));
    }

    // The first request may have finished between the lookup and the lock.
    if let Ok(Some(stored)) = store.get::<Stored>(&store_key).await {
        let _ = lock.release().await;
        return replay(stored, &fingerprint, request);
    }

    let response = inner(request).await;
    let response = remember(&store, &store_key, fingerprint, settings.ttl, response).await;
    let _ = lock.release().await;
    Ok(response)
}

fn store(name: Option<&str>) -> laravel::Result<Repository> {
    match name {
        Some(name) => laravel::cache::store(name),
        None => laravel::cache::manager().default_store(),
    }
}

fn replay(
    stored: Stored,
    fingerprint: &str,
    request: Request,
) -> Result<Response, Box<(ApiError, Request)>> {
    if stored.fingerprint != fingerprint {
        return Err(Box::new((
            ApiError::new(
                ApiErrorCode::IdempotencyKeyMismatch,
                "This Idempotency-Key was used for a different request. Use a new key for each new request.",
            )
            .header_source(HEADER),
            request,
        )));
    }
    let mut response = laravel::axum::http::Response::new(Body::from(
        STANDARD.decode(stored.body).unwrap_or_default(),
    ));
    *response.status_mut() = StatusCode::from_u16(stored.status).unwrap_or(StatusCode::OK);
    let headers = response.headers_mut();
    for (name, value) in stored.headers {
        if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
            headers.append(name, value);
        }
    }
    headers.insert(
        HeaderName::from_static(REPLAYED_HEADER),
        HeaderValue::from_static("true"),
    );
    Ok(Response::from_http(response))
}

/// Stores 2xx and 4xx responses. A 5xx or a 429 says nothing final about the request, so it is
/// not stored and the client can retry it.
async fn remember(
    store: &Repository,
    key: &str,
    fingerprint: String,
    ttl: u64,
    response: Response,
) -> Response {
    let http = response.into_http();
    let status = http.status().as_u16();
    // PHP checks scopes before it looks at the key, so a scope error is not kept either.
    let denied = laravel::context::get_hidden::<bool>(crate::auth::DENIED).unwrap_or(false);
    let storable = !denied
        && ((200..300).contains(&status) || ((400..500).contains(&status) && status != 429));
    if !storable {
        return Response::from_http(http);
    }
    let (parts, body) = http.into_parts();
    let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
    let stored = Stored {
        fingerprint,
        status,
        headers: parts
            .headers
            .iter()
            .filter(|(name, _)| !UNSTORED_HEADERS.contains(&name.as_str()))
            .filter_map(|(name, value)| {
                Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
            })
            .collect(),
        body: STANDARD.encode(&bytes),
    };
    // A store that can't be written only loses the replay; the request itself succeeded.
    let _ = store.put(key, &stored, Duration::from_secs(ttl)).await;
    Response::from_http(laravel::axum::http::Response::from_parts(
        parts,
        Body::from(bytes),
    ))
}