dregs 1.0.0

The official Rust client for Dregs, which scores the users of your application for fraud and abuse.
Documentation
//! Send a backend event to Dregs.
//!
//! Run it with your credential's secret key in the environment:
//!
//! ```text
//! DREGS_SECRET_KEY=sk_... cargo run --example track_event
//! ```

use dregs::{ApiErrorKind, Client, Event};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), dregs::Error> {
    let client = Client::from_env()?;

    let event = Event::new("user.signup", "user_12345")
        // Attributes of the event.
        .data(json!({ "plan": "pro", "referrer": "partner-x" }))
        // Attributes of the user. The analyzers lean on these, so send what you have.
        .identity_data(json!({
            "email": "ada@example.com",
            "name": "Ada Lovelace",
            "username": "ada",
        }))
        // Your own id for the event makes ingestion idempotent: resending this exact call is a
        // no-op rather than a second signup.
        .event_id("signup-991");

    let result = match client.track(event).await {
        Ok(result) => result,
        Err(error) => {
            match error.kind() {
                Some(ApiErrorKind::QuotaExceeded) => {
                    println!("Over the monthly event limit. The event was not recorded.")
                }
                Some(ApiErrorKind::RateLimited) => {
                    let wait = error.api_error().and_then(|api| api.retry_after);
                    println!("Rate limited. Retry after {wait:?}.");
                }
                _ => println!("Could not reach Dregs: {error}"),
            }

            return Ok(());
        }
    };

    if result.accepted() {
        println!("Recorded event {}.", result.id.unwrap_or_default());
    } else {
        // Uncommon, and worth a log line: accepted without an event being recorded.
        println!("The event was not recorded (status {:?}).", result.status);
    }

    Ok(())
}