Each chat channel action the brain's tool asked for and each schedule delivery is recorded in activity/<day>.jsonl by kind, target, who asked and outcome, never its text, kept 30 days. The worker's chat_action carries the asker. A 한 일 screen lists the newest entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
674 lines
30 KiB
Rust
674 lines
30 KiB
Rust
//! Reminders and scheduled tasks (`app/src/admin.spec.md`, "Schedules"): the store in the data
|
|
//! folder, the next times, the brain's `schedule_action`, and the loop that fires and delivers.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
use std::time::Duration;
|
|
|
|
use chrono::{Datelike, Local, NaiveDateTime, TimeZone, Weekday};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{json, Value};
|
|
|
|
use crate::worker_client::ScheduleAction;
|
|
|
|
/// A schedule later than this when its time comes (the app was off, the PC asleep) is not delivered.
|
|
pub const GRACE_SECS: i64 = 15 * 60;
|
|
/// Schedules one person may have.
|
|
pub const PER_PERSON: usize = 50;
|
|
pub const MAX_TEXT_CHARS: usize = 500;
|
|
/// How often the loop looks for schedules that are due.
|
|
pub const TICK: Duration = Duration::from_secs(5);
|
|
|
|
/// The store's file is read and written whole; one change at a time in this process (the services'
|
|
/// loop and the settings screen both use it).
|
|
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Outcome {
|
|
pub at: i64,
|
|
pub ok: bool,
|
|
/// Why it failed, for the screen (no text of the schedule).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub note: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Schedule {
|
|
pub id: u64,
|
|
pub user: u64,
|
|
pub name: String,
|
|
/// `remind` or `task`.
|
|
pub kind: String,
|
|
pub text: String,
|
|
/// `none`, `daily`, `weekdays` or `weekly`.
|
|
pub repeat: String,
|
|
/// When it fires next (Unix seconds); None: it will not fire again (kept to show its outcome).
|
|
pub next: Option<i64>,
|
|
/// `voice` or `chat`: where it was asked.
|
|
pub via: String,
|
|
/// The chat channel it was asked in (via chat).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub channel: Option<u64>,
|
|
pub created: i64,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub last: Option<Outcome>,
|
|
/// Handed out by `take_due` and not finished yet; still set at the next start means the app
|
|
/// stopped while delivering it (`recover`).
|
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
pub firing: bool,
|
|
}
|
|
|
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct File {
|
|
next_id: u64,
|
|
items: Vec<Schedule>,
|
|
}
|
|
|
|
pub struct Store {
|
|
file: PathBuf,
|
|
}
|
|
|
|
/// The local time `t` (Unix seconds) one day, a weekday or a week on, at the same wall time.
|
|
fn step(t: i64, repeat: &str) -> i64 {
|
|
let local = Local.timestamp_opt(t, 0).single().unwrap_or_else(Local::now);
|
|
let wall = local.naive_local();
|
|
let mut day = wall.date();
|
|
loop {
|
|
day = day.succ_opt().unwrap_or(day);
|
|
let ok = match repeat {
|
|
"weekdays" => !matches!(day.weekday(), Weekday::Sat | Weekday::Sun),
|
|
"weekly" => day.weekday() == wall.weekday() && day != wall.date(),
|
|
_ => true,
|
|
};
|
|
if ok {
|
|
break;
|
|
}
|
|
}
|
|
let at = NaiveDateTime::new(day, wall.time());
|
|
// A wall time a clock change skips is taken an hour later.
|
|
Local.from_local_datetime(&at).earliest()
|
|
.or_else(|| Local.from_local_datetime(&(at + chrono::Duration::hours(1))).earliest())
|
|
.map(|d| d.timestamp()).unwrap_or(t + 86_400)
|
|
}
|
|
|
|
fn is_weekend(t: i64) -> bool {
|
|
Local.timestamp_opt(t, 0).single().is_some_and(|d| matches!(d.weekday(), Weekday::Sat | Weekday::Sun))
|
|
}
|
|
|
|
/// The first time a schedule asked for `at` fires: `at` itself, the next weekday for `weekdays`,
|
|
/// and for a repeating one that has passed, its first time after `now`.
|
|
pub fn first_time(at: i64, repeat: &str, now: i64) -> i64 {
|
|
let mut t = at;
|
|
if repeat == "weekdays" && is_weekend(t) {
|
|
t = step(t, repeat);
|
|
}
|
|
while repeat != "none" && t <= now {
|
|
t = step(t, repeat);
|
|
}
|
|
t
|
|
}
|
|
|
|
/// What `take_due` hands out to deliver.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Due {
|
|
pub item: Schedule,
|
|
/// The time it was due (the item's `next` has moved on for a repeating one).
|
|
pub due: i64,
|
|
}
|
|
|
|
impl Store {
|
|
pub fn new(data: &Path) -> Self {
|
|
Self { file: data.join("config").join("schedules.json") }
|
|
}
|
|
|
|
fn load(&self) -> Result<File, String> {
|
|
match std::fs::read_to_string(&self.file) {
|
|
Ok(t) => serde_json::from_str(&t).map_err(|e| format!("예약 파일을 읽을 수 없습니다: {e}")),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(File::default()),
|
|
Err(e) => Err(format!("예약 파일을 읽을 수 없습니다: {e}")),
|
|
}
|
|
}
|
|
|
|
fn save(&self, f: &File) -> Result<(), String> {
|
|
let mut text = serde_json::to_string_pretty(f).unwrap();
|
|
text.push('\n');
|
|
crate::datadir::write_atomic(&self.file, text.as_bytes()).map_err(|e| format!("예약 파일을 쓸 수 없습니다: {e}"))
|
|
}
|
|
|
|
fn change<T>(&self, f: impl FnOnce(&mut File) -> Result<T, String>) -> Result<T, String> {
|
|
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
let mut file = self.load()?;
|
|
let out = f(&mut file)?;
|
|
self.save(&file)?;
|
|
Ok(out)
|
|
}
|
|
|
|
/// Every schedule, soonest first (those that will not fire again last).
|
|
pub fn all(&self) -> Result<Vec<Schedule>, String> {
|
|
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
let mut items = self.load()?.items;
|
|
items.sort_by_key(|i| (i.next.is_none(), i.next, i.id));
|
|
Ok(items)
|
|
}
|
|
|
|
/// One person's schedules, soonest first.
|
|
pub fn of(&self, user: u64) -> Result<Vec<Schedule>, String> {
|
|
Ok(self.all()?.into_iter().filter(|i| i.user == user).collect())
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn add(&self, user: u64, name: &str, kind: &str, text: &str, at: i64, repeat: &str, via: &str,
|
|
channel: Option<u64>, now: i64) -> Result<Schedule, String> {
|
|
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
|
if text.is_empty() || text.chars().count() > MAX_TEXT_CHARS {
|
|
return Err(format!("text must be 1-{MAX_TEXT_CHARS} characters"));
|
|
}
|
|
if !["remind", "task"].contains(&kind) {
|
|
return Err("kind must be remind or task".into());
|
|
}
|
|
if !["none", "daily", "weekdays", "weekly"].contains(&repeat) {
|
|
return Err("repeat must be none, daily, weekdays or weekly".into());
|
|
}
|
|
let channel = match via {
|
|
"voice" => None,
|
|
"chat" => Some(channel.ok_or("a chat schedule needs the channel it was asked in")?),
|
|
_ => return Err("via must be voice or chat".into()),
|
|
};
|
|
if repeat == "none" && at <= now {
|
|
return Err("that time has already passed".into());
|
|
}
|
|
let next = first_time(at, repeat, now);
|
|
self.change(|f| {
|
|
if f.items.iter().filter(|i| i.user == user && i.next.is_some()).count() >= PER_PERSON {
|
|
return Err(format!("at most {PER_PERSON} schedules per person; delete one first"));
|
|
}
|
|
f.next_id += 1;
|
|
let item = Schedule { id: f.next_id, user, name: name.to_owned(), kind: kind.into(), text,
|
|
repeat: repeat.into(), next: Some(next), via: via.into(), channel, created: now, last: None,
|
|
firing: false };
|
|
f.items.push(item.clone());
|
|
Ok(item)
|
|
})
|
|
}
|
|
|
|
/// Delete a schedule; with `user`, only one of theirs.
|
|
pub fn delete(&self, id: u64, user: Option<u64>) -> Result<Schedule, String> {
|
|
self.change(|f| {
|
|
let pos = f.items.iter().position(|i| i.id == id && user.is_none_or(|u| u == i.user))
|
|
.ok_or_else(|| "no such schedule of this person".to_string())?;
|
|
Ok(f.items.remove(pos))
|
|
})
|
|
}
|
|
|
|
/// The schedules due at `now`. A repeating one is judged by its latest time up to `now` (the
|
|
/// ones before it, while the app was off, are passed over) and moves on to its next time; a
|
|
/// one-off one stops (`next` None). Each one handed out is `firing` until `finished` records how
|
|
/// it went. One more than `GRACE_SECS` late is not handed out and is recorded as missed.
|
|
pub fn take_due(&self, now: i64) -> Result<Vec<Due>, String> {
|
|
let _g = FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
let mut file = self.load()?;
|
|
let mut due = vec![];
|
|
let mut changed = false;
|
|
for item in file.items.iter_mut() {
|
|
let Some(mut t) = item.next.filter(|t| *t <= now) else { continue };
|
|
changed = true;
|
|
if item.repeat != "none" {
|
|
loop {
|
|
let n = step(t, &item.repeat);
|
|
if n > now {
|
|
break;
|
|
}
|
|
t = n;
|
|
}
|
|
}
|
|
item.next = (item.repeat != "none").then(|| first_time(t, &item.repeat, now));
|
|
if now - t > GRACE_SECS {
|
|
item.last = Some(Outcome { at: now, ok: false, note: Some("앱이 꺼져 있어 제때 전하지 못함".into()) });
|
|
crate::warn_log!("schedule", "Warning: schedule {} missed ({} s late)", item.id, now - t);
|
|
} else {
|
|
item.firing = true;
|
|
due.push(Due { item: item.clone(), due: t });
|
|
}
|
|
}
|
|
if changed {
|
|
self.save(&file)?;
|
|
}
|
|
Ok(due)
|
|
}
|
|
|
|
/// Record how a delivery went. A one-off schedule delivered is removed; one that failed stays
|
|
/// (not firing again) so the screen shows it.
|
|
pub fn finished(&self, id: u64, outcome: Outcome) -> Result<(), String> {
|
|
self.change(|f| {
|
|
if let Some(pos) = f.items.iter().position(|i| i.id == id) {
|
|
if outcome.ok && f.items[pos].next.is_none() {
|
|
f.items.remove(pos);
|
|
} else {
|
|
f.items[pos].last = Some(outcome);
|
|
f.items[pos].firing = false;
|
|
}
|
|
}
|
|
Ok(())
|
|
})
|
|
}
|
|
}
|
|
|
|
impl Store {
|
|
/// At start: the schedules a previous run handed out and never finished (it stopped while
|
|
/// delivering them) get a failed outcome. How many.
|
|
pub fn recover(&self, now: i64) -> Result<usize, String> {
|
|
self.change(|f| {
|
|
let mut n = 0;
|
|
for i in f.items.iter_mut().filter(|i| i.firing) {
|
|
i.firing = false;
|
|
i.last = Some(Outcome { at: now, ok: false, note: Some("전하는 도중 앱이 멈춤".into()) });
|
|
crate::warn_log!("schedule", "Warning: schedule {} was being delivered when the app stopped", i.id);
|
|
n += 1;
|
|
}
|
|
Ok(n)
|
|
})
|
|
}
|
|
}
|
|
|
|
/// A schedule as the brain's tool sees it.
|
|
pub fn brain_item(s: &Schedule) -> Value {
|
|
json!({"id": s.id.to_string(), "kind": s.kind, "text": s.text, "repeat": s.repeat,
|
|
"next": s.next.map(|t| t as f64)})
|
|
}
|
|
|
|
/// Do what the brain's schedule tool asked for the person in `a.user` (named `name`): the item(s)
|
|
/// for its result, or why not.
|
|
pub fn act(store: &Store, a: &ScheduleAction, name: &str, now: i64) -> Result<Value, String> {
|
|
let user: u64 = a.user.parse().map_err(|_| "bad user id".to_string())?;
|
|
match a.action.as_str() {
|
|
"list" => Ok(json!({"items": store.of(user)?.iter().filter(|s| s.next.is_some()).map(brain_item).collect::<Vec<_>>()})),
|
|
"delete" => {
|
|
let id: u64 = a.schedule.as_deref().and_then(|s| s.trim().parse().ok()).ok_or("delete needs the schedule's id")?;
|
|
Ok(json!({"item": brain_item(&store.delete(id, Some(user))?)}))
|
|
}
|
|
"add" => {
|
|
let at = a.at.filter(|t| t.is_finite()).ok_or("add needs at")?;
|
|
let channel = a.channel.as_deref().and_then(|c| c.parse().ok());
|
|
let s = store.add(user, name, a.kind.as_deref().unwrap_or("remind"), a.text.as_deref().unwrap_or(""),
|
|
at.round() as i64, a.repeat.as_deref().unwrap_or("none"), &a.via, channel, now)?;
|
|
crate::info_log!("schedule", "schedule {} added: {} {} by {user}", s.id, s.kind, s.repeat);
|
|
Ok(json!({"item": brain_item(&s)}))
|
|
}
|
|
other => Err(format!("unknown schedule action {other}")),
|
|
}
|
|
}
|
|
|
|
/// What the loop needs to deliver (the Discord core; a fake in tests).
|
|
#[async_trait::async_trait]
|
|
pub trait Deliver: Send + Sync {
|
|
/// The person is in Jarvis's voice channel.
|
|
fn hears(&self, user: u64) -> bool;
|
|
/// Speak in the voice channel and wait until it was heard to the end; false when not in one,
|
|
/// or when the speech failed or was stopped.
|
|
async fn say(&self, text: &str) -> bool;
|
|
/// Post in a registered chat channel (never pinging anyone).
|
|
async fn post(&self, channel: u64, text: &str) -> Result<(), String>;
|
|
/// Run a task in the brain (read-only tools) and wait for its answer.
|
|
async fn task(&self, id: &str, user: u64, text: &str) -> Option<String>;
|
|
}
|
|
|
|
/// Deliver one due schedule: a task runs first; then by voice when it was asked by voice and the
|
|
/// person is in Jarvis's voice channel, else in the chat channel it was asked in, or for voice the
|
|
/// fallback channel (`schedule.chatChannel`).
|
|
pub async fn deliver(d: &dyn Deliver, due: &Due, fallback: Option<u64>) -> Outcome {
|
|
let s = &due.item;
|
|
let now = || chrono::Utc::now().timestamp();
|
|
let fail = |note: &str| Outcome { at: now(), ok: false, note: Some(note.into()) };
|
|
let body = if s.kind == "task" {
|
|
match d.task(&format!("s{}-{}", s.id, due.due), s.user, &s.text).await {
|
|
Some(a) if !a.trim().is_empty() => a,
|
|
_ => return fail("작업 결과를 만들지 못함"),
|
|
}
|
|
} else {
|
|
s.text.clone()
|
|
};
|
|
let text = format!("{}님, {}", s.name, body.trim());
|
|
// Speech that did not finish goes to the chat channel like a person who is not there.
|
|
if s.via == "voice" && d.hears(s.user) && d.say(&text).await {
|
|
crate::debug_log!("schedule", "schedule {} spoken chars={}", s.id, text.chars().count());
|
|
return Outcome { at: now(), ok: true, note: None };
|
|
}
|
|
let Some(channel) = (if s.via == "chat" { s.channel } else { fallback }) else {
|
|
return fail("음성 채널에 없고 알림 채팅 채널이 정해지지 않음");
|
|
};
|
|
match d.post(channel, &text).await {
|
|
Ok(()) => {
|
|
crate::debug_log!("schedule", "schedule {} posted in {channel} chars={}", s.id, text.chars().count());
|
|
Outcome { at: now(), ok: true, note: None }
|
|
}
|
|
Err(e) => {
|
|
crate::warn_log!("schedule", "Warning: schedule {} could not be posted in {channel}: {e}", s.id);
|
|
fail("채팅 채널에 보내지 못함")
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Record how a delivery went: in the store (its outcome) and in the activity log (kind, id, who
|
|
/// asked and the outcome; never the text).
|
|
pub fn finish(store: &Store, activity: &crate::activity::Activity, due: &Due, out: Outcome) {
|
|
let s = &due.item;
|
|
crate::info_log!("schedule", "schedule {} {}", s.id, if out.ok { "delivered" } else { "not delivered" });
|
|
activity.record(&format!("schedule.{}", s.kind), &format!("예약 {}", s.id), Some(format!("{} {}", s.user, s.name)),
|
|
out.ok, out.note.clone());
|
|
if let Err(e) = store.finished(s.id, out) {
|
|
crate::warn_log!("schedule", "Warning: {e}");
|
|
}
|
|
}
|
|
|
|
/// Fire due schedules until the task is aborted. Each delivery runs on its own, so a slow task does
|
|
/// not hold up a reminder due meanwhile; aborting the loop aborts the deliveries it started (they
|
|
/// are recorded as interrupted at the next start, `recover`).
|
|
pub async fn run(store: std::sync::Arc<Store>, activity: std::sync::Arc<crate::activity::Activity>,
|
|
d: std::sync::Arc<dyn Deliver>, fallback: Option<u64>) {
|
|
if let Err(e) = store.recover(chrono::Utc::now().timestamp()) {
|
|
crate::warn_log!("schedule", "Warning: {e}");
|
|
}
|
|
let mut deliveries = tokio::task::JoinSet::new();
|
|
loop {
|
|
while deliveries.try_join_next().is_some() {}
|
|
match store.take_due(chrono::Utc::now().timestamp()) {
|
|
Ok(due) => for item in due {
|
|
let (store, activity, d) = (store.clone(), activity.clone(), d.clone());
|
|
deliveries.spawn(async move {
|
|
let out = deliver(d.as_ref(), &item, fallback).await;
|
|
finish(&store, &activity, &item, out);
|
|
});
|
|
},
|
|
Err(e) => {
|
|
crate::warn_log!("schedule", "Warning: {e}");
|
|
}
|
|
}
|
|
tokio::time::sleep(TICK).await;
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use chrono::Timelike;
|
|
use std::sync::Arc;
|
|
|
|
fn local(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> i64 {
|
|
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).earliest().unwrap().timestamp()
|
|
}
|
|
|
|
fn store() -> Store {
|
|
Store::new(&crate::datadir::temp_dir("schedule"))
|
|
}
|
|
|
|
#[test]
|
|
fn repeats_keep_the_wall_time_and_skip_what_they_leave_out() {
|
|
// 2026-11-13 is a Friday.
|
|
let fri = local(2026, 11, 13, 9, 0);
|
|
assert_eq!(step(fri, "daily"), local(2026, 11, 14, 9, 0));
|
|
assert_eq!(step(fri, "weekdays"), local(2026, 11, 16, 9, 0));
|
|
assert_eq!(step(fri, "weekly"), local(2026, 11, 20, 9, 0));
|
|
// Asked for a Saturday on weekdays: Monday. A daily one that passed: its next time.
|
|
assert_eq!(first_time(local(2026, 11, 14, 9, 0), "weekdays", 0), local(2026, 11, 16, 9, 0));
|
|
assert_eq!(first_time(fri, "daily", local(2026, 11, 15, 10, 0)), local(2026, 11, 16, 9, 0));
|
|
assert_eq!(Local.timestamp_opt(step(fri, "daily"), 0).unwrap().hour(), 9);
|
|
}
|
|
|
|
#[test]
|
|
fn a_person_sees_and_deletes_only_their_own() {
|
|
let s = store();
|
|
let a = s.add(1, "가", "remind", " 회의 준비 ", 2000, "none", "voice", None, 1000).unwrap();
|
|
let b = s.add(2, "나", "task", "날씨", 3000, "daily", "chat", Some(77), 1000).unwrap();
|
|
assert_eq!(a.text, "회의 준비");
|
|
assert_eq!(s.of(1).unwrap(), vec![a.clone()]);
|
|
assert!(s.delete(b.id, Some(1)).is_err());
|
|
assert_eq!(s.delete(b.id, None).unwrap(), b);
|
|
assert_eq!(s.all().unwrap(), vec![a]);
|
|
}
|
|
|
|
#[test]
|
|
fn bad_adds_are_refused() {
|
|
let s = store();
|
|
for (kind, text, at, repeat, via, channel) in [
|
|
("remind", "", 2000, "none", "voice", None),
|
|
("remind", "x", 500, "none", "voice", None),
|
|
("alarm", "x", 2000, "none", "voice", None),
|
|
("remind", "x", 2000, "hourly", "voice", None),
|
|
("remind", "x", 2000, "none", "chat", None),
|
|
] {
|
|
assert!(s.add(1, "가", kind, text, at, repeat, via, channel, 1000).is_err(), "{kind} {text} {repeat} {via}");
|
|
}
|
|
assert!(s.add(1, "가", "remind", &"x".repeat(MAX_TEXT_CHARS + 1), 2000, "none", "voice", None, 1000).is_err());
|
|
for _ in 0..PER_PERSON {
|
|
s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).unwrap();
|
|
}
|
|
assert!(s.add(1, "가", "remind", "x", 2000, "none", "voice", None, 1000).is_err());
|
|
assert!(s.add(2, "나", "remind", "x", 2000, "none", "voice", None, 1000).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn due_schedules_are_handed_out_once_and_late_ones_are_recorded_as_missed() {
|
|
let s = store();
|
|
let once = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
|
let daily = s.add(1, "가", "remind", "b", local(2026, 11, 13, 9, 0), "daily", "voice", None, 0).unwrap();
|
|
let late = s.add(1, "가", "remind", "c", 1500, "none", "voice", None, 1000).unwrap();
|
|
assert!(s.take_due(1499).unwrap().is_empty());
|
|
let now = local(2026, 11, 13, 9, 1);
|
|
let got: Vec<u64> = s.take_due(now).unwrap().into_iter().map(|d| d.item.id).collect();
|
|
// `once` and `late` were due long before `now`: missed. The daily one moves to tomorrow.
|
|
assert_eq!(got, vec![daily.id]);
|
|
assert!(s.take_due(now).unwrap().is_empty());
|
|
let all = s.all().unwrap();
|
|
let find = |id| all.iter().find(|i| i.id == id).unwrap().clone();
|
|
assert_eq!(find(daily.id).next, Some(local(2026, 11, 14, 9, 0)));
|
|
for id in [once.id, late.id] {
|
|
let i = find(id);
|
|
assert_eq!(i.next, None);
|
|
assert!(!i.last.unwrap().ok);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_delivered_one_off_schedule_is_removed_and_a_failed_one_kept() {
|
|
let s = store();
|
|
let a = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
|
let b = s.add(1, "가", "remind", "b", 2000, "none", "voice", None, 1000).unwrap();
|
|
assert_eq!(s.take_due(2000).unwrap().len(), 2);
|
|
s.finished(a.id, Outcome { at: 2001, ok: true, note: None }).unwrap();
|
|
s.finished(b.id, Outcome { at: 2001, ok: false, note: Some("x".into()) }).unwrap();
|
|
let all = s.all().unwrap();
|
|
assert_eq!(all.len(), 1);
|
|
assert_eq!(all[0].id, b.id);
|
|
assert!(!all[0].last.as_ref().unwrap().ok);
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Fake {
|
|
hears: bool,
|
|
/// The speech does not finish (it failed or was stopped).
|
|
speech_fails: bool,
|
|
/// task() never answers; `hung` is set while it waits and cleared when it is dropped.
|
|
hang: bool,
|
|
hung: Arc<std::sync::atomic::AtomicBool>,
|
|
said: Mutex<Vec<String>>,
|
|
posted: Mutex<Vec<(u64, String)>>,
|
|
post_fails: bool,
|
|
answer: Option<String>,
|
|
tasks: Mutex<Vec<(u64, String)>>,
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl Deliver for Fake {
|
|
fn hears(&self, _user: u64) -> bool {
|
|
self.hears
|
|
}
|
|
async fn say(&self, text: &str) -> bool {
|
|
self.said.lock().unwrap().push(text.into());
|
|
!self.speech_fails
|
|
}
|
|
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
|
|
if self.post_fails {
|
|
return Err("no".into());
|
|
}
|
|
self.posted.lock().unwrap().push((channel, text.into()));
|
|
Ok(())
|
|
}
|
|
async fn task(&self, _id: &str, user: u64, text: &str) -> Option<String> {
|
|
self.tasks.lock().unwrap().push((user, text.into()));
|
|
if self.hang {
|
|
struct Clear(Arc<std::sync::atomic::AtomicBool>);
|
|
impl Drop for Clear {
|
|
fn drop(&mut self) {
|
|
self.0.store(false, std::sync::atomic::Ordering::SeqCst);
|
|
}
|
|
}
|
|
self.hung.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
let _clear = Clear(self.hung.clone());
|
|
std::future::pending::<()>().await;
|
|
}
|
|
self.answer.clone()
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn speech_that_does_not_finish_falls_back_to_the_chat_channel_or_fails() {
|
|
let f = Fake { hears: true, speech_fails: true, ..Default::default() };
|
|
assert!(deliver(&f, &due("remind", "voice", None), Some(9)).await.ok);
|
|
assert_eq!(*f.posted.lock().unwrap(), vec![(9, "철수님, 회의".to_string())]);
|
|
let out = deliver(&f, &due("remind", "voice", None), None).await;
|
|
assert!(!out.ok && out.note.is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn a_repeating_schedule_the_app_was_off_for_still_fires_its_latest_time_when_recent() {
|
|
let s = store();
|
|
// Set on the 12th; the app was off until a minute after 9:00 on the 14th.
|
|
let d = s.add(1, "가", "remind", "b", local(2026, 11, 12, 9, 0), "daily", "voice", None,
|
|
local(2026, 11, 12, 8, 0)).unwrap();
|
|
let due = s.take_due(local(2026, 11, 14, 9, 1)).unwrap();
|
|
assert_eq!(due.iter().map(|d| (d.item.id, d.due)).collect::<Vec<_>>(), vec![(d.id, local(2026, 11, 14, 9, 0))]);
|
|
assert_eq!(s.all().unwrap()[0].next, Some(local(2026, 11, 15, 9, 0)));
|
|
// Off past the grace: that day's is missed, the next one stays.
|
|
let late = s.take_due(local(2026, 11, 15, 9, 30)).unwrap();
|
|
assert!(late.is_empty());
|
|
let item = s.all().unwrap()[0].clone();
|
|
assert_eq!(item.next, Some(local(2026, 11, 16, 9, 0)));
|
|
assert!(!item.last.unwrap().ok);
|
|
}
|
|
|
|
#[test]
|
|
fn a_schedule_taken_but_never_finished_is_recorded_as_interrupted_at_the_next_start() {
|
|
let s = store();
|
|
let a = s.add(1, "가", "remind", "a", 2000, "none", "voice", None, 1000).unwrap();
|
|
let b = s.add(1, "가", "remind", "b", 2000, "none", "voice", None, 1000).unwrap();
|
|
assert_eq!(s.take_due(2000).unwrap().len(), 2);
|
|
s.finished(b.id, Outcome { at: 2001, ok: false, note: Some("x".into()) }).unwrap();
|
|
// The app quit while `a` was being delivered.
|
|
assert_eq!(s.recover(3000).unwrap(), 1);
|
|
let all = s.all().unwrap();
|
|
let find = |id| all.iter().find(|i| i.id == id).unwrap().clone();
|
|
let last = find(a.id).last.unwrap();
|
|
assert!(!last.ok && last.note.is_some() && last.at == 3000);
|
|
assert_eq!(find(b.id).last.unwrap().note.as_deref(), Some("x"));
|
|
assert_eq!(s.recover(3001).unwrap(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_delivery_is_recorded_in_the_activity_without_its_text() {
|
|
let data = crate::datadir::temp_dir("schedule-activity");
|
|
let s = Store::new(&data);
|
|
let a = crate::activity::Activity::new(&data);
|
|
let item = s.add(5, "철수", "remind", "비밀 회의", 2000, "none", "voice", None, 1000).unwrap();
|
|
let due = s.take_due(2000).unwrap().remove(0);
|
|
finish(&s, &a, &due, Outcome { at: 2001, ok: false, note: Some("채팅 채널에 보내지 못함".into()) });
|
|
let got = a.recent(10);
|
|
assert_eq!(got.len(), 1);
|
|
assert_eq!((got[0].kind.as_str(), got[0].ok), ("schedule.remind", false));
|
|
assert_eq!(got[0].by.as_deref(), Some("5 철수"));
|
|
assert!(got[0].target.contains(&item.id.to_string()));
|
|
assert!(!serde_json::to_string(&got[0]).unwrap().contains("비밀"), "no text in the activity");
|
|
assert!(!s.all().unwrap()[0].last.as_ref().unwrap().ok, "the outcome is kept too");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn stopping_the_loop_stops_the_deliveries_it_started() {
|
|
let data = crate::datadir::temp_dir("schedule-run");
|
|
let s = Arc::new(Store::new(&data));
|
|
let now = chrono::Utc::now().timestamp();
|
|
s.add(1, "가", "task", "x", now + 1, "none", "chat", Some(77), now).unwrap();
|
|
let f = Arc::new(Fake { hang: true, ..Default::default() });
|
|
let run = tokio::spawn(run(s.clone(), Arc::new(crate::activity::Activity::new(&data)), f.clone(), None));
|
|
let hung = f.hung.clone();
|
|
tokio::time::timeout(Duration::from_secs(10), async {
|
|
while !hung.load(std::sync::atomic::Ordering::SeqCst) {
|
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
|
}
|
|
}).await.expect("the task started");
|
|
run.abort();
|
|
let _ = run.await;
|
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
|
assert!(!hung.load(std::sync::atomic::Ordering::SeqCst), "the delivery was not stopped");
|
|
assert!(f.posted.lock().unwrap().is_empty());
|
|
}
|
|
|
|
fn due(kind: &str, via: &str, channel: Option<u64>) -> Due {
|
|
Due { item: Schedule { id: 1, user: 5, name: "철수".into(), kind: kind.into(), text: "회의".into(),
|
|
repeat: "none".into(), next: None, via: via.into(), channel, created: 0, last: None, firing: false }, due: 10 }
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_voice_reminder_is_spoken_to_someone_there_and_posted_otherwise() {
|
|
let f = Fake { hears: true, ..Default::default() };
|
|
assert!(deliver(&f, &due("remind", "voice", None), Some(9)).await.ok);
|
|
assert_eq!(*f.said.lock().unwrap(), vec!["철수님, 회의".to_string()]);
|
|
let away = Fake::default();
|
|
assert!(deliver(&away, &due("remind", "voice", None), Some(9)).await.ok);
|
|
assert_eq!(*away.posted.lock().unwrap(), vec![(9, "철수님, 회의".to_string())]);
|
|
// Nowhere to go: not delivered, and says why.
|
|
let out = deliver(&away, &due("remind", "voice", None), None).await;
|
|
assert!(!out.ok && out.note.is_some());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_chat_reminder_goes_to_its_channel_even_when_the_person_is_in_voice() {
|
|
let f = Fake { hears: true, ..Default::default() };
|
|
assert!(deliver(&f, &due("remind", "chat", Some(77)), Some(9)).await.ok);
|
|
assert!(f.said.lock().unwrap().is_empty());
|
|
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 회의".to_string())]);
|
|
let fails = Fake { post_fails: true, ..Default::default() };
|
|
assert!(!deliver(&fails, &due("remind", "chat", Some(77)), None).await.ok);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_task_delivers_the_brains_answer_and_fails_without_one() {
|
|
let f = Fake { answer: Some("맑아요".into()), ..Default::default() };
|
|
assert!(deliver(&f, &due("task", "chat", Some(77)), None).await.ok);
|
|
assert_eq!(*f.tasks.lock().unwrap(), vec![(5, "회의".to_string())]);
|
|
assert_eq!(*f.posted.lock().unwrap(), vec![(77, "철수님, 맑아요".to_string())]);
|
|
let none = Fake::default();
|
|
let out = deliver(&none, &due("task", "chat", Some(77)), None).await;
|
|
assert!(!out.ok && none.posted.lock().unwrap().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn the_brains_actions_are_done_for_the_asker_only() {
|
|
let s = store();
|
|
let a = |action: &str, user: &str, extra: Value| -> ScheduleAction {
|
|
let mut v = json!({"id": "x", "action": action, "user": user, "via": "voice"});
|
|
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
|
serde_json::from_value(v).unwrap()
|
|
};
|
|
let added = act(&s, &a("add", "1", json!({"kind": "remind", "text": "물", "at": 2000.4, "repeat": "none"})), "가", 1000).unwrap();
|
|
assert_eq!(added["item"]["id"], "1");
|
|
assert_eq!(added["item"]["next"], 2000.0);
|
|
assert_eq!(act(&s, &a("list", "2", json!({})), "나", 1000).unwrap()["items"], json!([]));
|
|
assert!(act(&s, &a("delete", "2", json!({"schedule": "1"})), "나", 1000).is_err());
|
|
assert_eq!(act(&s, &a("list", "1", json!({})), "가", 1000).unwrap()["items"].as_array().unwrap().len(), 1);
|
|
assert!(act(&s, &a("delete", "1", json!({"schedule": "1"})), "가", 1000).is_ok());
|
|
assert!(act(&s, &a("add", "1", json!({"text": "x", "at": 2000.0, "via": "chat"})), "가", 1000).is_err());
|
|
}
|
|
}
|