glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! A stand-in for Stripe in development and tests: no network, no
//! account. A checkout is paid at once (its URL is the success URL), and
//! the objects it makes come back in Stripe's shapes, so the app's sync
//! and hooks run as they would for real.

use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

use serde_json::{Value as Json, json};

use super::{Checkout, CheckoutSession, Pending, Processor};
use crate::error::Error;

/// See the module docs.
#[derive(Default)]
pub struct Fake {
    next: AtomicU64,
    objects: Mutex<HashMap<String, Json>>,
}

impl Fake {
    fn id(&self, prefix: &str) -> String {
        format!(
            "{prefix}_fake_{}",
            self.next.fetch_add(1, Ordering::Relaxed) + 1
        )
    }

    fn keep(&self, object: Json) -> Json {
        let id = object["id"].as_str().unwrap_or_default().to_owned();
        self.objects
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(id, object.clone());
        object
    }

    fn get(&self, id: &str) -> crate::Result<Json> {
        self.objects
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)
            .cloned()
            .ok_or_else(|| Error::not_found_in("the fake processor", id))
    }
}

impl Error {
    fn not_found_in(place: &str, id: &str) -> Self {
        Error::new(http::StatusCode::NOT_FOUND, format!("no `{id}` in {place}"))
    }
}

impl Processor for Fake {
    fn create_customer<'a>(&'a self, email: &'a str) -> Pending<'a, String> {
        let id = self.id("cus");
        self.keep(json!({"id": id, "object": "customer", "email": email}));
        Box::pin(async move { Ok(id) })
    }

    fn create_checkout<'a>(
        &'a self,
        customer: &'a str,
        checkout: &'a Checkout,
    ) -> Pending<'a, CheckoutSession> {
        let metadata: serde_json::Map<String, Json> = checkout
            .metadata
            .iter()
            .map(|(k, v)| (k.clone(), json!(v)))
            .collect();
        let now = crate::time::now().timestamp();
        let session_id = self.id("cs");
        let mut session = json!({
            "id": session_id,
            "object": "checkout.session",
            "status": "complete",
            "mode": checkout.mode,
            "customer": customer,
            "metadata": metadata,
            "subscription": null,
            "payment_intent": null,
        });
        if checkout.mode == "subscription" {
            let subscription = self.keep(json!({
                "id": self.id("sub"),
                "object": "subscription",
                "customer": customer,
                "status": "active",
                "metadata": metadata,
                "current_period_start": now,
                "current_period_end": now + 30 * 24 * 3600,
                "cancel_at_period_end": false,
                "items": {"data": [{"price": {"id": checkout.price}, "quantity": checkout.quantity}]},
            }));
            session["subscription"] = subscription;
        } else {
            let charge = self.keep(json!({
                "id": self.id("ch"),
                "object": "charge",
                "customer": customer,
                "amount": 1000 * i64::from(checkout.quantity),
                "amount_refunded": 0,
                "currency": "usd",
                "paid": true,
                "metadata": metadata,
            }));
            session["payment_intent"] = json!({"id": self.id("pi"), "latest_charge": charge});
        }
        let session = self.keep(session);
        let url = checkout.success_url_with_id().replace(
            "{CHECKOUT_SESSION_ID}",
            session["id"].as_str().unwrap_or_default(),
        );
        Box::pin(async move {
            Ok(CheckoutSession {
                id: session_id,
                url,
            })
        })
    }

    fn checkout_session<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move { self.get(id) })
    }

    fn subscription<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move { self.get(id) })
    }

    fn charge<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move { self.get(id) })
    }
}