use super::error::{ProtocolError, ProtocolResult};
use crate::changes_simplifier::simplify_changes;
use crate::link::Link;
use crate::named_type_links::NamedTypeLinks;
use links_notation::binary::{format_document, format_link, LinoDocument};
use links_notation::LiNo;
pub const ANY: &str = "*";
pub type Part = Option<u32>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinksOperation {
Count(Vec<Part>),
Each(Vec<Part>),
Create { source: u32, target: u32 },
Update {
index: u32,
source: u32,
target: u32,
},
Delete(u32),
GetName(u32),
SetName(u32, String),
GetByName(String),
RemoveName(u32),
Subscribe(Vec<Part>),
Unsubscribe(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LinksNotification {
pub subscription: u32,
pub changes: Vec<Change>,
}
pub type Change = (Link, Link);
impl LinksOperation {
pub fn to_document(&self) -> LinoDocument {
let (name, argument) = match self {
Self::Count(restriction) => ("count", restriction_lino(restriction)),
Self::Each(restriction) => ("each", restriction_lino(restriction)),
Self::Create { source, target } => ("create", numbers_lino(&[*source, *target])),
Self::Update {
index,
source,
target,
} => ("update", numbers_lino(&[*index, *source, *target])),
Self::Delete(index) => ("delete", number(*index)),
Self::GetName(index) => ("get-name", number(*index)),
Self::SetName(index, name) => (
"set-name",
group(vec![number(*index), LiNo::Ref(name.clone())]),
),
Self::GetByName(name) => ("get-by-name", LiNo::Ref(name.clone())),
Self::RemoveName(index) => ("remove-name", number(*index)),
Self::Subscribe(restriction) => ("subscribe", restriction_lino(restriction)),
Self::Unsubscribe(subscription) => ("unsubscribe", number(*subscription)),
};
vec![named(name, vec![argument])]
}
pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
let [LiNo::Link {
id: Some(name),
values,
}] = document
else {
return Ok(None);
};
let [argument] = values.as_slice() else {
return Ok(None);
};
let operation = match name.as_str() {
"count" => Self::Count(parse_restriction(argument)?),
"each" => Self::Each(parse_restriction(argument)?),
"create" => {
let [source, target] = parse_numbers::<2>(argument)?;
Self::Create { source, target }
}
"update" => {
let [index, source, target] = parse_numbers::<3>(argument)?;
Self::Update {
index,
source,
target,
}
}
"delete" => Self::Delete(parse_number(argument)?),
"get-name" => Self::GetName(parse_number(argument)?),
"set-name" => match parts(argument) {
[index, LiNo::Ref(name)] => Self::SetName(parse_number(index)?, name.clone()),
_ => return Err(malformed_argument("set-name", argument)),
},
"get-by-name" => match argument {
LiNo::Ref(name) => Self::GetByName(name.clone()),
_ => return Err(malformed_argument("get-by-name", argument)),
},
"remove-name" => Self::RemoveName(parse_number(argument)?),
"subscribe" => Self::Subscribe(parse_restriction(argument)?),
"unsubscribe" => Self::Unsubscribe(parse_number(argument)?),
_ => return Ok(None),
};
Ok(Some(operation))
}
pub fn execute<S: NamedTypeLinks + ?Sized>(
&self,
storage: &mut S,
) -> anyhow::Result<LinoDocument> {
Ok(match self {
Self::Count(restriction) => {
let count = matching(storage, restriction).len();
vec![named("count", vec![LiNo::Ref(count.to_string())])]
}
Self::Each(restriction) => matching(storage, restriction)
.iter()
.map(link_lino)
.collect(),
Self::Create { source, target } => {
let created = Link::new(storage.try_create(*source, *target)?, *source, *target);
storage.save()?;
changes_document(&[(Link::null(), created)])
}
Self::Update {
index,
source,
target,
} => {
let mut changes = Vec::new();
storage.update_observed(*index, *source, *target, &mut |before, after| {
changes.push((before, after))
})?;
storage.save()?;
changes_document(&simplify_changes(changes))
}
Self::Delete(index) => {
let mut changes = Vec::new();
storage
.delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
storage.save()?;
changes_document(&simplify_changes(changes))
}
Self::GetName(index) => match storage.get_name(*index)? {
Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
None => Vec::new(),
},
Self::SetName(index, name) => {
let link = storage.set_name(*index, name)?;
storage.save()?;
link_reply(Some(link))
}
Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
Self::RemoveName(index) => {
storage.remove_name(*index)?;
storage.save()?;
Vec::new()
}
Self::Subscribe(_) | Self::Unsubscribe(_) => {
anyhow::bail!("subscriptions belong to a connection to a links server")
}
})
}
}
pub fn matches(link: &Link, restriction: &[Part]) -> bool {
let is = |part: Part, value: u32| part.is_none_or(|part| part == value);
match *restriction {
[] => true,
[index] => is(index, link.index),
[index, value] => {
is(index, link.index) && (is(value, link.source) || is(value, link.target))
}
[index, source, target] => {
is(index, link.index) && is(source, link.source) && is(target, link.target)
}
_ => false,
}
}
fn matching<S: NamedTypeLinks + ?Sized>(storage: &mut S, restriction: &[Part]) -> Vec<Link> {
let mut links = match restriction.first() {
Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
_ => storage.all_links(),
};
links.retain(|link| matches(link, restriction));
links.sort_by_key(|link| link.index);
links
}
pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
match document {
[LiNo::Link {
id: Some(id),
values,
}] if id == "count" => match values.as_slice() {
[count] => parse_number(count),
_ => Err(malformed_reply("count", document)),
},
_ => Err(malformed_reply("count", document)),
}
}
pub fn parse_subscription(document: &[LiNo<String>]) -> ProtocolResult<u32> {
match document {
[LiNo::Link {
id: Some(id),
values,
}] if id == "subscription" => match values.as_slice() {
[subscription] => parse_number(subscription),
_ => Err(malformed_reply("subscription", document)),
},
_ => Err(malformed_reply("subscription", document)),
}
}
pub fn subscription_document(subscription: u32) -> LinoDocument {
vec![named("subscription", vec![number(subscription)])]
}
pub fn is_notification(document: &[LiNo<String>]) -> bool {
notification_number(document).is_some()
}
pub(super) fn notification_number(document: &[LiNo<String>]) -> Option<u32> {
match document.first()? {
LiNo::Link {
id: Some(id),
values,
} if id == "notify" => match values.as_slice() {
[LiNo::Ref(text)] if text.bytes().all(|byte| byte.is_ascii_digit()) => {
text.parse().ok()
}
_ => None,
},
_ => None,
}
}
pub fn notification_document(subscription: u32, changes: &[Change]) -> LinoDocument {
let mut document = vec![named("notify", vec![number(subscription)])];
document.extend(changes_document(changes));
document
}
pub fn parse_notification(document: &[LiNo<String>]) -> ProtocolResult<LinksNotification> {
let subscription =
notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
Ok(LinksNotification {
subscription,
changes: parse_changes(&document[1..])?,
})
}
pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
document.iter().map(parse_link).collect()
}
pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
document
.iter()
.map(|change| match parts(change) {
[before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
_ => Err(malformed_reply("change", document)),
})
.collect()
}
pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
match document {
[] => Ok(None),
[LiNo::Link {
id: Some(id),
values,
}] if id == "name" => match values.as_slice() {
[LiNo::Ref(name)] => Ok(Some(name.clone())),
_ => Err(malformed_reply("name", document)),
},
_ => Err(malformed_reply("name", document)),
}
}
pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
match document {
[] => Ok(None),
[LiNo::Link {
id: Some(id),
values,
}] if id == "link" => match values.as_slice() {
[link] => parse_number(link).map(Some),
_ => Err(malformed_reply("link", document)),
},
_ => Err(malformed_reply("link", document)),
}
}
pub fn changes_document(changes: &[Change]) -> LinoDocument {
changes
.iter()
.map(|(before, after)| group(vec![change_side(before), change_side(after)]))
.collect()
}
pub fn link_lino(link: &Link) -> LiNo<String> {
named(
&link.index.to_string(),
vec![number(link.source), number(link.target)],
)
}
fn link_reply(link: Option<u32>) -> LinoDocument {
link.map(|link| vec![named("link", vec![number(link)])])
.unwrap_or_default()
}
fn change_side(link: &Link) -> LiNo<String> {
if link.is_null() {
group(Vec::new())
} else {
group(vec![link_lino(link)])
}
}
fn parse_change_side(side: &LiNo<String>) -> ProtocolResult<Link> {
match side {
LiNo::Link { id: None, values } if values.is_empty() => Ok(Link::null()),
LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
_ => Err(ProtocolError::malformed(format!(
"expected a change side, found {}",
format_link(side)
))),
}
}
fn parse_link(link: &LiNo<String>) -> ProtocolResult<Link> {
match link {
LiNo::Link {
id: Some(index),
values,
} => match values.as_slice() {
[source, target] => Ok(Link::new(
parse_text_number(index)?,
parse_number(source)?,
parse_number(target)?,
)),
_ => Err(ProtocolError::malformed(format!(
"expected (index: source target), found {}",
format_link(link)
))),
},
_ => Err(ProtocolError::malformed(format!(
"expected (index: source target), found {}",
format_link(link)
))),
}
}
pub(super) fn restriction_lino(restriction: &[Part]) -> LiNo<String> {
group(
restriction
.iter()
.map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
.collect(),
)
}
fn parse_restriction(argument: &LiNo<String>) -> ProtocolResult<Vec<Part>> {
parse_restriction_of(argument, 3)
}
pub(super) fn parse_restriction_of(
argument: &LiNo<String>,
longest: usize,
) -> ProtocolResult<Vec<Part>> {
let parts = parts(argument);
if parts.len() > longest {
return Err(malformed_argument("restriction", argument));
}
parts
.iter()
.map(|part| match part {
LiNo::Ref(text) if text == ANY => Ok(None),
part => parse_number(part).map(Some),
})
.collect()
}
pub(super) fn numbers_lino(numbers: &[u32]) -> LiNo<String> {
group(numbers.iter().copied().map(number).collect())
}
pub(super) fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
let numbers = parts(argument)
.iter()
.map(parse_number)
.collect::<ProtocolResult<Vec<_>>>()?;
numbers
.try_into()
.map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
}
pub(super) fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
match argument {
LiNo::Link { id: None, values } => values,
reference => std::slice::from_ref(reference),
}
}
pub(super) fn parse_number(value: &LiNo<String>) -> ProtocolResult<u32> {
match value {
LiNo::Ref(text) => parse_text_number(text),
_ => Err(ProtocolError::malformed(format!(
"expected a number, found {}",
format_link(value)
))),
}
}
pub(super) fn parse_text_number(text: &str) -> ProtocolResult<u32> {
text.parse()
.map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
}
pub(super) fn number(value: u32) -> LiNo<String> {
LiNo::Ref(value.to_string())
}
pub(super) fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
LiNo::Link {
id: Some(id.to_string()),
values,
}
}
pub(super) fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
LiNo::Link { id: None, values }
}
pub(super) fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
ProtocolError::malformed(format!(
"expected {expected}, found {}",
format_link(argument)
))
}
pub(super) fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
ProtocolError::malformed(format!(
"expected a {expected} reply, found {}",
format_document(document)
))
}