use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::{ActionAddress, RemoteActionTarget};
pub const PROVIDER: &str = "tilo.telling";
pub const IMPORTANCE: &str = "importance";
pub const TOLD: &str = "told";
pub const READ: &str = "read";
pub const SAY: &str = "say";
pub const UNSAY: &str = "unsay";
pub const SET_FACT: &str = "set-fact";
pub const FORGET_FACT: &str = "forget-fact";
pub const SET_INSISTING: &str = "set-insisting";
pub const LET_THROUGH: &str = "let-through";
pub const KEEP_ON_HOST: &str = "keep-on-host";
pub const TELL: &str = "tell";
pub const LIST: &str = "list";
pub const ACKNOWLEDGE: &str = "acknowledge";
pub const INSIST: &str = "insist";
pub const SINCE_YOU_LEFT: &str = "since-you-left";
pub const CAUSE_REMINDER: &str = "reminder";
pub const CAUSE_BRIEF: &str = "brief";
pub const CAUSE_EVENT: &str = "event";
pub const CAUSE_PERSON: &str = "person";
pub const MAX_LINES: usize = 50;
pub const MAX_FACTS: usize = 50;
pub const MAX_LINE_BYTES: usize = 500;
pub const MAX_FACT_NAME_BYTES: usize = 80;
pub const MAX_FACT_VALUE_BYTES: usize = 200;
pub const MAX_WORDS_BYTES: usize = 600;
pub const MAX_TITLE_BYTES: usize = 120;
pub const MAX_ACTIONS: usize = 6;
pub const MIN_INSIST_SECS: u64 = 60;
pub const MAX_INSIST_SECS: u64 = 24 * 60 * 60;
pub const MAX_INSIST_TIMES: u32 = 24;
pub const MAX_LIST_WAIT_MS: u64 = 10_000;
#[must_use]
pub fn target(resource: &str, action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(resource, action),
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Importance {
#[serde(default)]
pub lines: Vec<Line>,
#[serde(default)]
pub facts: Vec<Fact>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub through_quiet: Vec<Reach>,
#[serde(default)]
pub insists: Insisting,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kept_on_host: Vec<String>,
#[serde(default)]
pub revision: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Line {
pub id: String,
pub words: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub only_while: Option<Holds>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub by: String,
#[serde(default)]
pub at_ms: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Holds {
pub fact: String,
pub is: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Fact {
pub name: String,
pub value: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub by: String,
#[serde(default)]
pub at_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Insisting {
pub every_secs: u64,
pub times: u32,
}
impl Default for Insisting {
fn default() -> Self {
Self {
every_secs: 10 * 60,
times: 6,
}
}
}
impl Insisting {
pub fn checked(self) -> Result<Self, String> {
if !(MIN_INSIST_SECS..=MAX_INSIST_SECS).contains(&self.every_secs) {
return Err("A reminder repeats between once a minute and once a day".to_owned());
}
if !(1..=MAX_INSIST_TIMES).contains(&self.times) {
return Err(format!(
"A reminder repeats at most {MAX_INSIST_TIMES} times"
));
}
Ok(self)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
Question,
Reminder,
Brief,
#[default]
News,
Mention,
}
impl Kind {
#[must_use]
pub fn of_cause(cause: Option<&Cause>) -> Self {
match cause.map(|cause| cause.kind.as_str()) {
Some(CAUSE_REMINDER) => Self::Reminder,
Some(CAUSE_BRIEF) => Self::Brief,
_ => Self::News,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Reach {
Question,
Reminder,
Brief,
Important,
Mention,
}
impl Reach {
#[must_use]
pub const fn of(kind: Kind, important: bool) -> Option<Self> {
match kind {
Kind::Question => Some(Self::Question),
Kind::Reminder => Some(Self::Reminder),
Kind::Brief => Some(Self::Brief),
Kind::Mention => Some(Self::Mention),
Kind::News if important => Some(Self::Important),
Kind::News => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Decided<'a> {
NoRule,
NothingHolds(Option<(&'a str, &'a str)>),
Judge(Vec<&'a Line>),
}
fn same(left: &str, right: &str) -> bool {
left.trim().to_lowercase() == right.trim().to_lowercase()
}
impl Importance {
#[must_use]
pub fn fact(&self, name: &str) -> Option<&Fact> {
self.facts.iter().find(|fact| same(&fact.name, name))
}
#[must_use]
pub fn holds(&self, line: &Line) -> bool {
line.only_while.as_ref().is_none_or(|holds| {
self.fact(&holds.fact)
.is_some_and(|fact| same(&fact.value, &holds.is))
})
}
#[must_use]
pub fn decided(&self) -> Decided<'_> {
if self.lines.is_empty() {
return Decided::NoRule;
}
let holding: Vec<&Line> = self.lines.iter().filter(|line| self.holds(line)).collect();
if !holding.is_empty() {
return Decided::Judge(holding);
}
let mut waited = self
.lines
.iter()
.filter_map(|line| line.only_while.as_ref())
.map(|holds| holds.fact.as_str());
let first = waited.next();
let one = first
.filter(|first| waited.all(|name| same(name, first)))
.map(|name| {
self.fact(name)
.map_or((name, ""), |fact| (fact.name.as_str(), fact.value.as_str()))
});
Decided::NothingHolds(one)
}
#[must_use]
pub fn lets_through(&self, reach: Reach) -> bool {
self.through_quiet.contains(&reach)
}
#[must_use]
pub fn carries_outside(&self, workspace: &str) -> bool {
!self.kept_on_host.iter().any(|kept| kept == workspace)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Say {
pub words: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub only_while: Option<Holds>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Unsay {
pub line: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SetFact {
pub name: String,
pub value: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ForgetFact {
pub name: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LetThrough {
pub kind: Reach,
pub may: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct KeepOnHost {
pub workspace: String,
pub kept: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Cause {
pub kind: String,
#[serde(default)]
pub label: String,
#[serde(default)]
pub key: String,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WhyCode {
Question,
Reminder,
Brief,
#[default]
NoRule,
NothingHolds,
Judged,
Unjudged,
Mention,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Why {
pub code: WhyCode,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub fact: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub value: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub words: String,
}
impl Why {
#[must_use]
pub fn of(code: WhyCode) -> Self {
Self {
code,
..Self::default()
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mark {
pub important: bool,
pub why: Why,
#[serde(default)]
pub revision: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct About {
pub workspace: String,
pub app: String,
#[serde(default)]
pub record: String,
#[serde(default)]
pub resource: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TaskRef {
pub record: String,
pub issue: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Teller {
pub agent: String,
pub name: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OfferedTarget {
pub app: String,
#[serde(default)]
pub record: String,
pub resource: String,
pub action: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Offered {
pub id: String,
pub label: String,
#[serde(default)]
pub main: bool,
pub target: OfferedTarget,
#[serde(default)]
pub arguments: Map<String, Value>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Insists {
pub every_secs: u64,
pub times: u32,
pub raised: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_at_ms: Option<u64>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Acknowledged {
pub at_ms: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub device: String,
pub by: String,
}
pub const BY_OPENED: &str = "opened";
pub const BY_DISMISSED: &str = "dismissed";
pub const BY_ANSWERED: &str = "answered";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Pushed {
pub at_ms: u64,
pub by: String,
pub took: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Told {
pub seq: u64,
pub id: String,
pub at_ms: u64,
pub kind: Kind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<Teller>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub title: String,
pub words: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub about: Option<About>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task: Option<TaskRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cause: Option<Cause>,
pub mark: Mark,
pub reaches: bool,
#[serde(default)]
pub through_quiet: bool,
#[serde(default)]
pub outside: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<Offered>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub offered_by: Option<Teller>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub insists: Option<Insists>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acknowledged: Option<Acknowledged>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub withdrawn_at_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub pushed: Vec<Pushed>,
}
impl Told {
#[must_use]
pub const fn waits(&self) -> bool {
self.reaches && self.acknowledged.is_none() && self.withdrawn_at_ms.is_none()
}
}
#[must_use]
pub fn words_outside(told: &Told) -> (String, String) {
let name = told
.from
.as_ref()
.map(|from| from.name.trim())
.filter(|name| !name.is_empty());
let title = if told.title.trim().is_empty() {
match (told.kind, name) {
(Kind::Question, Some(name)) => format!("{name} needs you"),
(Kind::Question, None) => "An agent needs you".to_owned(),
(Kind::Mention, Some(name)) => format!("{name} mentioned you"),
(_, Some(name)) => name.to_owned(),
(_, None) => "Tilo".to_owned(),
}
} else {
told.title.trim().to_owned()
};
let body = if told.outside {
told.words.clone()
} else {
"Open Tilo to see it.".to_owned()
};
(title, body)
}
#[must_use]
pub fn known_as(auth: &[u8], id: &str) -> String {
let key = blake3::hash(auth);
let mut hasher = blake3::Hasher::new_keyed(key.as_bytes());
hasher.update(b"tilo told\0");
hasher.update(id.as_bytes());
let tag = hasher.finalize();
tag.to_hex().get(..16).unwrap_or_default().to_owned()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Tell {
pub words: String,
#[serde(default)]
pub title: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cause: Option<Cause>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub about: Option<About>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task: Option<TaskRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<Offered>,
#[serde(default)]
pub insists: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ListAfter {
#[serde(default)]
pub after: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait_ms: Option<u64>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub device: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToldList {
pub told: Vec<Told>,
pub newest: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Acknowledge {
pub told: String,
#[serde(default)]
pub device: String,
#[serde(default)]
pub by: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Insist {
pub told: String,
pub insists: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Stretch {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub left_at_ms: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub back_at_ms: Option<u64>,
pub came_in: Vec<Told>,
pub did_alone: Vec<Told>,
pub waits: Vec<Told>,
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::panic,
reason = "in a test these are the assertion, not a hazard"
)]
use super::*;
fn line(words: &str, only_while: Option<(&str, &str)>) -> Line {
Line {
id: words.len().to_string(),
words: words.to_owned(),
only_while: only_while.map(|(fact, is)| Holds {
fact: fact.to_owned(),
is: is.to_owned(),
}),
..Line::default()
}
}
fn fact(name: &str, value: &str) -> Fact {
Fact {
name: name.to_owned(),
value: value.to_owned(),
..Fact::default()
}
}
#[test]
fn nothing_said_is_no_rule() {
assert_eq!(Importance::default().decided(), Decided::NoRule);
}
#[test]
fn a_line_waits_on_its_situation() {
let mut rule = Importance {
lines: vec![line(
"A new customer is important only while we are hiring",
Some(("hiring", "yes")),
)],
facts: vec![fact("Hiring", "no")],
..Importance::default()
};
assert_eq!(
rule.decided(),
Decided::NothingHolds(Some(("Hiring", "no")))
);
rule.facts = vec![fact("Hiring", " Yes ")];
let Decided::Judge(holding) = rule.decided() else {
panic!("the line counts now");
};
assert_eq!(holding.len(), 1);
rule.facts.clear();
assert_eq!(rule.decided(), Decided::NothingHolds(Some(("hiring", ""))));
}
#[test]
fn a_plain_line_always_counts() {
let waiting = line("Only while travelling", Some(("travelling", "yes")));
let other = line("Only at quarter end", Some(("quarter end", "yes")));
let plain = line("My landlord is always important", None);
let rule = Importance {
lines: vec![waiting.clone(), plain.clone()],
..Importance::default()
};
assert_eq!(rule.decided(), Decided::Judge(vec![&plain]));
let rule = Importance {
lines: vec![waiting, other],
..Importance::default()
};
assert_eq!(rule.decided(), Decided::NothingHolds(None));
}
#[test]
fn a_cause_says_what_a_thing_is() {
let caused = |kind: &str| Cause {
kind: kind.to_owned(),
..Cause::default()
};
assert_eq!(Kind::of_cause(Some(&caused("reminder"))), Kind::Reminder);
assert_eq!(Kind::of_cause(Some(&caused("brief"))), Kind::Brief);
assert_eq!(Kind::of_cause(Some(&caused("event"))), Kind::News);
assert_eq!(Kind::of_cause(Some(&caused("competitors"))), Kind::News);
assert_eq!(Kind::of_cause(None), Kind::News);
assert_eq!(Reach::of(Kind::News, false), None);
assert_eq!(Reach::of(Kind::News, true), Some(Reach::Important));
assert_eq!(Reach::of(Kind::Reminder, false), Some(Reach::Reminder));
assert_eq!(Reach::of(Kind::Question, false), Some(Reach::Question));
assert_eq!(Reach::of(Kind::Brief, false), Some(Reach::Brief));
}
#[test]
fn a_told_thing_reads_as_written() {
let told = Told {
seq: 3,
id: "t1".into(),
kind: Kind::News,
words: "The quarterly figures arrived.".into(),
mark: Mark {
important: false,
why: Why {
code: WhyCode::NothingHolds,
fact: "Hiring".into(),
value: "no".into(),
words: String::new(),
},
revision: 2,
},
..Told::default()
};
let json = serde_json::to_value(&told).unwrap();
assert_eq!(json["kind"], "news");
assert_eq!(json["mark"]["why"]["code"], "nothing-holds");
assert_eq!(json["mark"]["why"]["fact"], "Hiring");
assert_eq!(json["reaches"], false);
assert!(json.get("acknowledged").is_none(), "{json}");
assert_eq!(serde_json::from_value::<Told>(json).unwrap(), told);
let letting: LetThrough =
serde_json::from_value(serde_json::json!({"kind": "reminder", "may": true})).unwrap();
assert_eq!(letting.kind, Reach::Reminder);
}
#[test]
fn insisting_is_bounded() {
assert!(Insisting::default().checked().is_ok());
let often = Insisting {
every_secs: 5,
times: 3,
};
assert!(often.checked().is_err());
let endless = Insisting {
every_secs: 600,
times: 1000,
};
assert!(endless.checked().is_err());
}
}