// An API's health panel: requests a minute, the average time they took, the error rate over five
// minutes and against the five before; and a 7-day moving average of daily sales from the database.
//
//   quillo run rolling_windows.qwe      then open http://localhost:8080/health
//
// A live app calls rolling_add("requests", ms, 0) in each request; here the last ten minutes are
// played in at fixed times, so the numbers are the same on every run.

use "rolling_windows.qwer"

let T = 1793836800000

fn replay() {
    for i in range(120) {
        rolling_add("requests", float(20 + (i % 10) * 5), T - i * 5000)?
        if i % 8 == 0 { rolling_add("errors", 1.0, T - i * 5000)? }
    }
}

route GET /health {
    if rolling_stats("requests", 3600, T)?.count == 0 { replay() }
    let minute = rolling_stats("requests", 60, T)?
    {
        last_minute: { requests: minute.count, mean_ms: minute.mean, slowest_ms: minute.max },
        error_rate_5m: rolling_ratio("errors", "requests", 300, T)?,
        errors_trend: rolling_trend("errors", 300, "count", T)?,
        per_minute: rolling_series("requests", 60, 60, 10, T)? | map((w) => w.count),
    }
}

// Daily sales rows (as a query would give them), and their 7-day moving average.
route GET /sales {
    let day = 86400000
    let rows = for d in range(14) => { at: T + d * day, value: float(100 + d * 10) }
    rolling_over(rows, 7 * 86400, 86400)? | map((w) => { day: (w.at - T) / day, sum: w.sum, mean: w.mean })
}
