use super::{
ActionCallError, ActionProvider, Caller, InvocationReceipt, InvokeArgument, InvokeRequest,
Pending, ReceiptStatus, RemoteActionTarget,
};
use crate::api::ActionAddress;
pub const PROVIDER: &str = "tilo.search";
pub const RESOURCE: &str = "search";
pub const FIND: &str = "find";
pub const PICTURES: &str = "pictures";
pub const DESCRIBE: &str = "describe";
#[must_use]
pub fn target() -> RemoteActionTarget {
target_of(FIND)
}
fn target_of(action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, action),
}
}
#[must_use]
pub fn is_search(target: &RemoteActionTarget) -> bool {
target.provider == PROVIDER
&& target.address.resource == RESOURCE
&& [FIND, PICTURES, DESCRIBE].contains(&target.address.action.as_str())
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Picture {
pub resource: String,
pub app: String,
pub workspace: String,
pub record: String,
pub image: String,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Description {
pub picture: Picture,
pub title: String,
pub words: Vec<(String, IndexWeight)>,
}
fn request_of(
invocation: super::InvocationId,
action: &str,
argument: Option<serde_json::Value>,
) -> InvokeRequest {
InvokeRequest {
invocation,
target: target_of(action),
argument: match argument {
Some(serde_json::Value::Object(fields)) => InvokeArgument::Json(fields),
_ => InvokeArgument::None,
},
context: None,
confirmation: None,
revision: None,
on_behalf_of: None,
wait_ms: None,
appearance: None,
signed: None,
}
}
#[must_use]
pub fn pictures_request(invocation: super::InvocationId) -> InvokeRequest {
request_of(invocation, PICTURES, None)
}
#[must_use]
pub fn describe_request(
invocation: super::InvocationId,
description: &Description,
) -> InvokeRequest {
request_of(invocation, DESCRIBE, serde_json::to_value(description).ok())
}
#[must_use]
pub fn is_find(target: &RemoteActionTarget) -> bool {
target.provider == PROVIDER
&& target.address.resource == RESOURCE
&& target.address.action == FIND
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Query {
pub needle: String,
#[serde(default, skip_serializing_if = "Within::is_everything")]
pub within: Within,
}
impl Query {
#[must_use]
pub fn request(
invocation: super::InvocationId,
needle: &str,
within: &Within,
) -> InvokeRequest {
let query = Self {
needle: needle.to_owned(),
within: within.clone(),
};
request_of(invocation, FIND, serde_json::to_value(query).ok())
}
pub fn of(request: &InvokeRequest) -> Result<Self, ActionCallError> {
let InvokeArgument::Json(fields) = &request.argument else {
return Err(ActionCallError::InvalidRequest {
reason: "a search is asked with its words: `needle`".into(),
});
};
serde_json::from_value(serde_json::Value::Object(fields.clone())).map_err(|error| {
ActionCallError::InvalidRequest {
reason: format!("a search is asked with `needle` and `within`: {error}"),
}
})
}
}
#[must_use]
pub fn receipt<T: serde::Serialize>(
invocation: super::InvocationId,
found: Result<T, ActionCallError>,
) -> InvocationReceipt {
let status = match found.and_then(|found| {
serde_json::to_value(found).map_err(|error| ActionCallError::Unavailable {
reason: format!("the search's answer could not be written: {error}"),
})
}) {
Ok(value) => ReceiptStatus::Completed {
output: crate::ActionOutput {
value: Some(value),
resources: Vec::new(),
},
},
Err(error) => ReceiptStatus::Rejected { error },
};
InvocationReceipt { invocation, status }
}
pub fn found(receipt: InvocationReceipt) -> Result<Vec<Found>, ActionCallError> {
match receipt.status {
ReceiptStatus::Completed { output } => output
.value
.and_then(|value| serde_json::from_value(value).ok())
.ok_or_else(|| ActionCallError::Unavailable {
reason: "the search answered no results".into(),
}),
ReceiptStatus::Rejected { error } => Err(error),
_ => Err(ActionCallError::Unavailable {
reason: "the search did not answer".into(),
}),
}
}
pub fn searched<H: ActionProvider + ?Sized>(
provider: &H,
caller: &Caller,
request: &InvokeRequest,
) -> Pending<InvocationReceipt> {
let invocation = request.invocation;
let Some(search) = provider.resource_search() else {
return Pending::ready(receipt::<()>(
invocation,
Err(ActionCallError::Unavailable {
reason: "this provider holds no records to search".into(),
}),
));
};
match request.target.address.action.as_str() {
PICTURES => search
.pictures(caller)
.map(move |pictures| receipt(invocation, pictures)),
DESCRIBE => match argument::<Description>(request) {
Ok(description) => search
.describe(caller, description)
.map(move |described| receipt(invocation, described)),
Err(error) => Pending::ready(receipt::<()>(invocation, Err(error))),
},
_ => match Query::of(request) {
Ok(query) => search
.find_within(caller, &query.needle, &query.within)
.map(move |found| receipt(invocation, found)),
Err(error) => Pending::ready(receipt::<()>(invocation, Err(error))),
},
}
}
fn argument<T: serde::de::DeserializeOwned>(request: &InvokeRequest) -> Result<T, ActionCallError> {
let fields = match &request.argument {
InvokeArgument::Json(fields) => fields.clone(),
_ => serde_json::Map::new(),
};
serde_json::from_value(serde_json::Value::Object(fields)).map_err(|error| {
ActionCallError::InvalidRequest {
reason: format!(
"the search's `{}` does not read: {error}",
request.target.address.action
),
}
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Found {
pub resource: String,
pub kind: String,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub open: Option<String>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub arguments: serde_json::Map<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub when: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subtitle: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub about: Option<IndexKind>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub people: Vec<IndexPerson>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub place: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rank: Option<i32>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub item: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexWeight {
Title,
Identity,
Subtitle,
Metadata,
Body,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexKind {
Agent,
Conversation,
Message,
Person,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct IndexPerson {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub anchor: String,
pub identity: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub agent: bool,
}
pub const FOUND_FILE: &str = "file";
pub const NOT_NARROWED: &str =
"this search cannot be narrowed to a conversation or a time: search by words alone";
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Within {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub place: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub before: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub about: Vec<IndexKind>,
}
impl Within {
#[must_use]
pub fn is_everything(&self) -> bool {
self.place.is_none() && self.app.is_none() && self.about.is_empty() && !self.is_timed()
}
#[must_use]
pub const fn is_timed(&self) -> bool {
self.after.is_some() || self.before.is_some()
}
#[must_use]
pub fn holds(&self, place: Option<(&str, &str)>, when: Option<i64>) -> bool {
self.holds_in(place, None, when)
}
#[must_use]
pub fn holds_in(
&self,
place: Option<(&str, &str)>,
owner: Option<(&str, &str)>,
when: Option<i64>,
) -> bool {
let placed = self.place.as_deref().is_none_or(|wanted| {
place.is_some_and(|(published, known)| wanted == published || wanted == known)
|| owner.is_some_and(|(address, holder)| {
inside(wanted, address) || inside(wanted, holder)
})
});
let timed = !self.is_timed()
|| when.is_some_and(|when| {
self.after.is_none_or(|after| when >= after)
&& self.before.is_none_or(|before| when < before)
});
placed && timed
}
#[must_use]
pub fn moment(text: &str) -> Option<i64> {
let text = text.trim();
if let Ok(moment) = text.parse::<jiff::Timestamp>() {
return Some(moment.as_second());
}
let day = jiff::civil::Date::strptime("%Y-%m-%d", text).ok()?;
Some(
day.to_zoned(jiff::tz::TimeZone::UTC)
.ok()?
.timestamp()
.as_second(),
)
}
#[must_use]
pub fn said_at(when: i64) -> Option<String> {
jiff::Timestamp::from_second(when)
.ok()
.map(|moment| format!("{moment:.0}"))
}
}
fn inside(scope: &str, address: &str) -> bool {
beneath(scope, address)
|| beneath(bare(scope), bare(address))
|| beneath(scope, bare(address))
|| beneath(bare(scope), address)
}
fn bare(id: &str) -> &str {
id.strip_prefix("tl:")
.and_then(|rest| rest.split_once(':'))
.map_or(id, |(_, id)| id)
}
fn beneath(scope: &str, address: &str) -> bool {
address
.strip_prefix(scope)
.is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
}
pub trait ResourceSearch: Send + Sync {
fn find(
&self,
caller: &super::Caller,
needle: &str,
) -> super::Pending<Result<Vec<Found>, ActionCallError>>;
fn find_within(
&self,
caller: &super::Caller,
needle: &str,
within: &Within,
) -> super::Pending<Result<Vec<Found>, ActionCallError>> {
if within.is_everything() {
return self.find(caller, needle);
}
super::Pending::ready(Err(ActionCallError::Unavailable {
reason: NOT_NARROWED.into(),
}))
}
fn pictures(
&self,
_caller: &super::Caller,
) -> super::Pending<Result<Vec<Picture>, ActionCallError>> {
super::Pending::ready(Err(ActionCallError::Unavailable {
reason: "this search keeps no pictures".into(),
}))
}
fn describe(
&self,
_caller: &super::Caller,
_description: Description,
) -> super::Pending<Result<(), ActionCallError>> {
super::Pending::ready(Err(ActionCallError::Unavailable {
reason: "this search keeps no pictures".into(),
}))
}
}
#[must_use]
pub fn stem_word(word: &str) -> String {
let letters = word.chars().count();
let strip = |ending: &str, shortest: usize| -> Option<String> {
let kept = word.strip_suffix(ending)?;
(word.chars().count() >= shortest && kept.chars().count() >= 3).then(|| kept.to_owned())
};
if letters <= 3 {
return word.to_owned();
}
let inflected = strip("ing", 4)
.or_else(|| strip("ed", 5))
.map(|stemmed| (stemmed, true))
.or_else(|| strip("ies", 5).map(|stemmed| (format!("{stemmed}y"), false)))
.or_else(|| strip("es", 5).map(|stemmed| (stemmed, false)))
.or_else(|| {
(!word.ends_with("ss"))
.then(|| strip("s", 4))
.flatten()
.map(|stemmed| (stemmed, false))
});
let Some((mut stemmed, doubled)) = inflected else {
return word.to_owned();
};
if doubled && doubles_its_last_letter(&stemmed) {
stemmed.pop();
}
stemmed
}
fn doubles_its_last_letter(stem: &str) -> bool {
let mut doubled = stem.chars().rev().take(2);
matches!(
(doubled.next(), doubled.next()),
(Some(last), Some(previous))
if last == previous && !matches!(last, 'e' | 'l' | 's' | 'z')
)
}
#[cfg(test)]
mod tests {
use super::{Within, stem_word};
#[test]
fn a_search_is_narrowed_by_where_a_thing_is_and_when() {
let conversation = ("pad/threads/t1", "t1");
let last_week = Within {
place: Some("pad/threads/t1".into()),
after: Within::moment("2026-11-10"),
before: Within::moment("2026-11-17T00:00:00Z"),
app: None,
about: Vec::new(),
};
assert_eq!(last_week.after, Some(1_794_268_800));
let inside = Within::moment("2026-11-12T09:30:00+01:00");
assert!(last_week.holds(Some(conversation), inside));
let by_id = Within {
place: Some("t1".into()),
..Within::default()
};
assert!(by_id.holds(Some(conversation), None));
assert!(last_week.holds(Some(conversation), last_week.after));
assert!(!last_week.holds(Some(conversation), last_week.before));
assert!(!last_week.holds(Some(("pad/threads/t2", "t2")), inside));
assert!(!last_week.holds(Some(conversation), Within::moment("2026-11-09")));
assert!(!last_week.holds(None, inside));
assert!(!last_week.holds(Some(conversation), None));
assert!(Within::default().is_everything() && Within::default().holds(None, None));
assert!(!last_week.is_everything());
assert_eq!(
Within::said_at(1_794_268_800).as_deref(),
Some("2026-11-10T00:00:00Z")
);
assert_eq!(Within::moment("next week"), None);
}
#[test]
fn a_search_scoped_to_a_resource_holds_the_items_that_live_in_it() {
let book = Within {
place: Some("tl:so.tilo.ebook:book1".into()),
..Within::default()
};
let chapter = ("", "tl:so.tilo.ebook:book1/ch1");
assert!(book.holds_in(None, Some(chapter), None));
assert!(
book.holds_in(None, Some(("tl:so.tilo.ebook:book1/ch2", "")), None),
"the item's own address is under the scope as well"
);
assert!(
book.holds_in(None, Some(("", "book1/ch3")), None),
"an app hands the id it knows a resource by, without the app's name"
);
assert!(
!book.holds_in(None, Some(("", "book2/ch1")), None),
"another book's chapter is not inside it"
);
assert!(
!book.holds_in(None, None, None),
"what names nothing is outside a search narrowed to one place"
);
}
#[test]
fn a_stem_undoes_an_inflection_and_nothing_else() {
for (word, stem) in [
("drawing", "draw"),
("dragging", "drag"),
("dragged", "drag"),
("scrolling", "scroll"),
("scrolled", "scroll"),
("scrolls", "scroll"),
("signing", "sign"),
("signed", "sign"),
("signs", "sign"),
("presses", "press"),
("pressing", "press"),
("copies", "copy"),
] {
assert_eq!(stem_word(word), stem, "{word}");
}
for word in ["press", "ring", "thing", "id", "use", "scroll", "drag"] {
assert_eq!(stem_word(word), word, "{word}");
}
}
}