glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Deleting old records on a schedule, as Laravel's `Prunable` does:
//! a model says which of its records are old, and the jobs scheduler
//! deletes them, once an hour or as often as each prune says.
//!
//! ```ignore
//! impl Prunable for Session {
//!     fn prunes() -> Vec<Prune<Self>> {
//!         vec![
//!             Prune::new("", || {
//!                 Session::all().filter(|s| s.updated_at.lt(glacier::time::now() - 30.days()))
//!             }),
//!             Prune::new("guests", || Session::all().filter(|s| s.user_id.is_null()))
//!                 .every(1.days()),
//!         ]
//!     }
//! }
//!
//! Jobs::new().prune_records::<Session>()
//! ```
//!
//! A prune without hooks deletes with SQL, a batch at a time, so no
//! callbacks run. A prune with hooks (`.pruning(…)`) loads each record,
//! runs the hooks, then destroys it, so its `before_destroy` and
//! `after_destroy` callbacks and `dependent` associations run too.

use std::future::Future;
use std::pin::Pin;

use chrono::TimeDelta;

use super::Delay;
use crate::db::{Expr, Query, Value};
use crate::error::Result;
use crate::model::Model;

/// How many records each delete takes, so no statement holds locks long.
const BATCH: u64 = 1000;

/// What a pruning hook returns.
pub type HookFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

/// A hook run on each record a prune deletes, before it's destroyed.
pub type Hook<M> = for<'a> fn(&'a mut M) -> HookFuture<'a>;

/// A model whose old records are deleted on a schedule.
pub trait Prunable: Model {
    /// The model's prunes: which records each deletes, and how often.
    fn prunes() -> Vec<Prune<Self>>;
}

/// One of a model's prunes: `prune :old, every: 1.days() do … end`.
pub struct Prune<M> {
    name: &'static str,
    every: TimeDelta,
    query: fn() -> Query<M>,
    hooks: Vec<Hook<M>>,
}

impl<M> Clone for Prune<M> {
    fn clone(&self) -> Self {
        Self {
            name: self.name,
            every: self.every,
            query: self.query,
            hooks: self.hooks.clone(),
        }
    }
}

impl<M: Model> Prune<M> {
    /// A prune of the records `query` gives, once an hour. `name` tells
    /// a model's prunes apart (`""` for its only one); the logs and
    /// `prune_named` use `table:name`.
    pub fn new(name: &'static str, query: fn() -> Query<M>) -> Self {
        Self {
            name,
            every: TimeDelta::hours(1),
            query,
            hooks: Vec::new(),
        }
    }

    /// Runs this often instead of once an hour.
    #[must_use]
    pub fn every(mut self, every: impl Delay) -> Self {
        self.every = every.delay();
        self
    }

    /// Runs `hook` on each record before it's destroyed; with any hook,
    /// records are deleted one by one, with their callbacks.
    #[must_use]
    pub fn pruning(mut self, hook: Hook<M>) -> Self {
        self.hooks.push(hook);
        self
    }

    /// `orders`, or `orders:abandoned` for a named prune.
    pub fn full_name(&self) -> String {
        if self.name.is_empty() {
            M::TABLE.to_owned()
        } else {
            format!("{}:{}", M::TABLE, self.name)
        }
    }

    pub fn interval(&self) -> TimeDelta {
        self.every
    }

    /// Deletes the prune's records; how many it deleted.
    pub async fn run(&self) -> Result<u64> {
        if self.hooks.is_empty() {
            return self.delete_in_batches().await;
        }
        let mut deleted = 0;
        loop {
            let records = (self.query)().limit(BATCH).all().await?;
            let batch = records.len() as u64;
            for mut record in records {
                for hook in &self.hooks {
                    hook(&mut record).await?;
                }
                record.destroy().await?;
                deleted += 1;
            }
            if batch < BATCH {
                return Ok(deleted);
            }
        }
    }

    async fn delete_in_batches(&self) -> Result<u64> {
        let mut deleted = 0;
        loop {
            let ids = (self.query)().limit(BATCH).ids().await?;
            if ids.is_empty() {
                return Ok(deleted);
            }
            let batch = ids.len() as u64;
            let values = ids.into_iter().map(Value::Int).collect();
            deleted += Query::<M>::new()
                .filter(|_| Expr::In {
                    column: M::PRIMARY_KEY,
                    values,
                })
                .delete_all()
                .await?;
            if batch < BATCH {
                return Ok(deleted);
            }
        }
    }
}

/// Runs every one of `M`'s prunes; how many records they deleted.
pub async fn prune<M: Prunable>() -> Result<u64> {
    let mut deleted = 0;
    for prune in M::prunes() {
        deleted += prune.run().await?;
    }
    Ok(deleted)
}