AnyBot/src/schedule.rs

243 lines
13 KiB
Rust

// 日程 (laid out like OpenBot's 日程): every time a bot is set to do something — each bot's
// routines on a schedule and the workflows with a scheduled trigger — on one calendar: what ran
// and how it went (from their run records), and what is coming (from their schedules, the same
// way the scheduler works it out), so the person sees what each bot will do without asking it.
// Routines started by an event (a trigger) have no times ahead: only their runs show.
use crate::model::State;
use crate::routines::{self, RunOutcome};
use crate::workflow::{NodeKind, RunState};
/// What an entry is about.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum What {
Routine { bot: u64, id: u64 },
Workflow { id: u64 },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
Done,
Failed,
Stopped,
Running,
/// Will run then.
Coming,
/// Would run then, but it is paused.
Paused,
}
/// One time on the calendar.
#[derive(Clone, PartialEq, Debug)]
pub struct Item {
/// Seconds since 1970.
pub at: i64,
pub what: What,
/// The bot it belongs to (a workflow: the bot of its first step; 0 when it has none).
pub bot: u64,
pub title: String,
/// How it repeats (「每天 09:00」), or what starts it.
pub when: String,
pub status: Status,
}
/// At most this many times of one routine or workflow in one range: an hourly one fills the six
/// weeks a month shows (1,008); one every 5 minutes fills about four days.
pub const MAX_PER_THING: usize = 1_100;
/// Everything on the calendar from `from` up to `to` (seconds), oldest first: the runs that
/// started then, and — from `now` on — the times still to come.
pub fn items(state: &State, from: i64, to: i64, now: i64) -> Vec<Item> {
let mut out = vec![];
for b in &state.bots {
for r in &b.routines {
let what = What::Routine { bot: b.id, id: r.id };
let when = match &r.trigger {
Some(t) => t.describe(),
None => routines::describe(&r.schedule),
};
for run in r.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.outcome {
RunOutcome::Succeeded => Status::Done,
RunOutcome::Failed | RunOutcome::Interrupted => Status::Failed,
RunOutcome::Stopped => Status::Stopped,
RunOutcome::Running => Status::Running,
};
out.push(Item { at: run.started, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
if r.trigger.is_none() {
let status = if r.paused { Status::Paused } else { Status::Coming };
// (A time that came while its bot was busy: it runs once the bot is free — shown
// at its time until then.)
if let Some(due) = r.next_run.filter(|t| !r.paused && *t < now && *t >= from && *t < to) {
out.push(Item { at: due, what, bot: b.id, title: r.title.clone(), when: when.clone(), status: Status::Coming });
}
for at in times(&r.schedule, r.created_at, from.max(now), to) {
out.push(Item { at, what, bot: b.id, title: r.title.clone(), when: when.clone(), status });
}
}
}
}
for w in &state.workflows {
let what = What::Workflow { id: w.id };
let bot = w.order().iter().find_map(|n| match w.node(*n).map(|n| &n.kind) {
Some(NodeKind::Step { bot, .. } | NodeKind::Check { bot, .. } | NodeKind::Deliver { bot } | NodeKind::Media { bot, .. }) => Some(*bot),
Some(NodeKind::Output { bot, .. }) if *bot != 0 => Some(*bot),
_ => None,
});
let bot = bot.unwrap_or(0);
let when = w.trigger().map(|n| n.kind.words()).unwrap_or_else(|| "手動".into());
for run in w.runs.iter().filter(|x| x.started >= from && x.started < to) {
let status = match run.state {
RunState::Done => Status::Done,
RunState::Failed => Status::Failed,
RunState::Stopped => Status::Stopped,
RunState::Running | RunState::Waiting => Status::Running,
};
out.push(Item { at: run.started, what, bot, title: w.name.clone(), when: when.clone(), status });
}
if let Some(s) = w.schedule() {
for at in times(s, w.created_at, from.max(now), to) {
out.push(Item { at, what, bot, title: w.name.clone(), when: when.clone(), status: Status::Coming });
}
}
}
out.sort_by(|a, b| a.at.cmp(&b.at).then(a.title.cmp(&b.title)));
out
}
/// The next few times coming, across everything (即將執行): paused ones left out.
pub fn coming(state: &State, now: i64, n: usize) -> Vec<Item> {
// (From a day back: one whose time came while its bot was busy is still to run.)
let mut out: Vec<Item> = items(state, now - 86_400, now + 14 * 86_400, now).into_iter().filter(|i| i.status == Status::Coming).collect();
out.truncate(n);
out
}
/// The times a schedule runs after `from` and before `to`.
fn times(s: &routines::Schedule, created: i64, from: i64, to: i64) -> Vec<i64> {
let mut out = vec![];
let mut after = from - 1;
while out.len() < MAX_PER_THING {
match routines::next_run(s, created, after) {
Some(t) if t < to && t > after => {
out.push(t);
after = t;
}
_ => break,
}
}
out
}
/// Midnight of a day in a time zone, as seconds (the calendar's days are the person's days).
pub fn day_start(day: chrono::NaiveDate, timezone: &str) -> i64 {
use chrono::TimeZone;
let tz = routines::tz_of(timezone);
let midnight = day.and_hms_opt(0, 0, 0).unwrap_or_default();
match tz.from_local_datetime(&midnight) {
chrono::LocalResult::Single(t) | chrono::LocalResult::Ambiguous(t, _) => t.timestamp(),
// (A day that starts in a summer-time gap: an hour later.)
chrono::LocalResult::None => tz.from_local_datetime(&(midnight + chrono::Duration::hours(1))).earliest().map(|t| t.timestamp()).unwrap_or(0),
}
}
/// The day (in a time zone) a moment falls on.
pub fn day_of(at: i64, timezone: &str) -> chrono::NaiveDate {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).date_naive()).unwrap_or_default()
}
/// 「21:11」 in a time zone.
pub fn clock(at: i64, timezone: &str) -> String {
use chrono::TimeZone;
chrono::Utc.timestamp_opt(at, 0).single().map(|t| t.with_timezone(&routines::tz_of(timezone)).format("%H:%M").to_string()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::routines::{Routine, RoutineRun, Schedule};
fn sched(v: serde_json::Value) -> Schedule {
routines::validate(serde_json::from_value(v).unwrap()).unwrap()
}
fn routine(id: u64, title: &str, s: Schedule, created: i64) -> Routine {
serde_json::from_value(serde_json::json!({"id": id, "title": title, "prompt": "做事", "schedule": s, "created_at": created})).unwrap()
}
/// A week in Taipei: the daily one each day at its time, the workday one Monday to Friday,
/// the paused one as paused; what ran before now shows how it went; an event one only its
/// runs; a scheduled workflow with the bot of its first step.
#[test]
fn the_calendar_shows_what_ran_and_what_is_coming() {
let tz = "Asia/Taipei";
let mut st = State::demo();
st.workflows.clear();
for b in st.bots.iter_mut() {
b.routines.clear();
}
let mon = chrono::NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
let from = day_start(mon, tz);
let to = day_start(mon + chrono::Duration::days(7), tz);
let created = from - 30 * 86_400;
// Now: Saturday 21 at 12:00.
let now = day_start(mon + chrono::Duration::days(5), tz) + 12 * 3600;
let mut daily = routine(1, "競品掃描", sched(serde_json::json!({"frequency": "daily", "time": "08:30", "timezone": tz})), created);
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(4), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Succeeded, note: String::new(), steps: 3, failed_steps: 0, sent: 0, sends: vec![] });
daily.runs.push(RoutineRun { started: day_start(mon + chrono::Duration::days(5), tz) + 8 * 3600 + 1800, ended: 0, outcome: RunOutcome::Failed, note: "沒網路".into(), steps: 1, failed_steps: 1, sent: 0, sends: vec![] });
let workdays = routine(2, "晨報", sched(serde_json::json!({"frequency": "weekly", "daysOfWeek": ["MO", "TU", "WE", "TH", "FR"], "time": "09:00", "timezone": tz})), created);
let mut paused = routine(3, "週報", sched(serde_json::json!({"frequency": "daily", "time": "18:00", "timezone": tz})), created);
paused.paused = true;
let mut event = routine(4, "PR 合併", sched(serde_json::json!({"frequency": "daily", "time": "09:00", "timezone": tz})), created);
event.trigger = Some(crate::triggers::Trigger::Webhook { secret: "s".into() });
st.bots[0].routines = vec![daily, workdays, paused, event];
let bot = st.bots[0].id;
let mut w = crate::workflow::Workflow::new(1, "Threads 早報", created);
if let NodeKind::Trigger { schedule, .. } = &mut w.nodes[0].kind {
*schedule = Some(sched(serde_json::json!({"frequency": "daily", "time": "07:00", "timezone": tz})));
}
w.nodes.push(crate::workflow::Node { id: 2, kind: NodeKind::Step { bot, prompt: "找".into() }, x: 0.0, y: 190.0 });
w.connect(1, 2);
st.workflows.push(w);
let all = items(&st, from, to, now);
let of = |title: &str| all.iter().filter(|i| i.title == title).map(|i| (day_of(i.at, tz).format("%d").to_string(), clock(i.at, tz), i.status)).collect::<Vec<_>>();
// Before now only what ran; from now on the times coming (Saturday 08:30 is past).
assert_eq!(of("競品掃描"), vec![("20".into(), "08:30".into(), Status::Done), ("21".into(), "08:30".into(), Status::Failed), ("22".into(), "08:30".into(), Status::Coming)]);
assert!(of("晨報").is_empty(), "Saturday and Sunday: no workdays left this week");
assert_eq!(of("週報"), vec![("21".into(), "18:00".into(), Status::Paused), ("22".into(), "18:00".into(), Status::Paused)]);
assert!(of("PR 合併").is_empty(), "an event one has no times ahead");
assert_eq!(of("Threads 早報"), vec![("22".into(), "07:00".into(), Status::Coming)]);
assert!(all.iter().filter(|i| i.title == "Threads 早報").all(|i| i.bot == bot && i.what == What::Workflow { id: 1 }));
assert!(all.windows(2).all(|w| w[0].at <= w[1].at), "oldest first");
// 即將執行: across everything, paused left out.
let next = coming(&st, now, 4);
let day = |i: &Item| day_of(i.at, tz).format("%d").to_string();
assert_eq!(
next.iter().map(|i| (day(i), clock(i.at, tz), i.title.as_str())).collect::<Vec<_>>(),
vec![("22".into(), "07:00".into(), "Threads 早報"), ("22".into(), "08:30".into(), "競品掃描"), ("23".into(), "07:00".into(), "Threads 早報"), ("23".into(), "08:30".into(), "競品掃描")]
);
assert!(next.iter().all(|i| i.status == Status::Coming && i.title != "週報"));
assert!(next.windows(2).all(|w| w[0].at <= w[1].at));
// A time that came while its bot was busy (next_run still before now): shown at its time
// and first in 即將執行 until it runs.
let due = now - 3 * 3600;
st.bots[0].routines[1].next_run = Some(due);
assert!(items(&st, from, to, now).iter().any(|i| i.title == "晨報" && i.at == due && i.status == Status::Coming));
assert_eq!(coming(&st, now, 1)[0].at, due);
st.bots[0].routines[1].next_run = None;
// An hourly one fills the six weeks of a month.
let six_weeks = from + 42 * 86_400;
st.bots[0].routines.push(routine(6, "每小時", sched(serde_json::json!({"frequency": "hourly", "time": "00:15", "timezone": tz})), created));
let hourly: Vec<i64> = items(&st, from, six_weeks, from).iter().filter(|i| i.title == "每小時").map(|i| i.at).collect();
assert_eq!(hourly.len(), 42 * 24);
assert!(*hourly.last().unwrap() > six_weeks - 3600);
st.bots[0].routines.retain(|r| r.id != 6);
// One every 5 minutes: capped.
st.bots[0].routines.push(routine(5, "盯盤", sched(serde_json::json!({"frequency": "minutely", "interval": 5, "time": "00:00", "timezone": tz})), created));
assert_eq!(items(&st, from, from + 42 * 86_400, now).iter().filter(|i| i.title == "盯盤").count(), MAX_PER_THING);
}
}