1use super::error::{ProtocolError, ProtocolResult};
43use crate::changes_simplifier::simplify_generic_changes;
44use crate::link::{GenericLink, Link};
45use crate::named_type_links::NamedTypeLinks;
46use crate::query_address::QueryAddress;
47use links_notation::binary::{format_document, format_link, LinoDocument};
48use links_notation::LiNo;
49
50pub const ANY: &str = "*";
52
53pub type Part<T = u32> = Option<T>;
55
56#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum GenericLinksOperation<T> {
59 Count(Vec<Part<T>>),
61 Each(Vec<Part<T>>),
63 Create { source: T, target: T },
65 Update { index: T, source: T, target: T },
68 Delete(T),
70 GetName(T),
72 SetName(T, String),
74 GetByName(String),
76 RemoveName(T),
78 Subscribe(Vec<Part<T>>),
85 Unsubscribe(T),
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct LinksNotification {
99 pub subscription: u32,
101 pub changes: Vec<Change>,
103}
104
105pub type Change<T = u32> = (GenericLink<T>, GenericLink<T>);
107
108pub type LinksOperation = GenericLinksOperation<u32>;
110
111impl<T: QueryAddress> GenericLinksOperation<T> {
112 pub fn to_document(&self) -> LinoDocument {
114 let (name, argument) = match self {
115 Self::Count(restriction) => ("count", restriction_lino(restriction)),
116 Self::Each(restriction) => ("each", restriction_lino(restriction)),
117 Self::Create { source, target } => ("create", numbers_lino(&[*source, *target])),
118 Self::Update {
119 index,
120 source,
121 target,
122 } => ("update", numbers_lino(&[*index, *source, *target])),
123 Self::Delete(index) => ("delete", number(*index)),
124 Self::GetName(index) => ("get-name", number(*index)),
125 Self::SetName(index, name) => (
126 "set-name",
127 group(vec![number(*index), LiNo::Ref(name.clone())]),
128 ),
129 Self::GetByName(name) => ("get-by-name", LiNo::Ref(name.clone())),
130 Self::RemoveName(index) => ("remove-name", number(*index)),
131 Self::Subscribe(restriction) => ("subscribe", restriction_lino(restriction)),
132 Self::Unsubscribe(subscription) => ("unsubscribe", number(*subscription)),
133 };
134 vec![named(name, vec![argument])]
135 }
136
137 pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
140 let [LiNo::Link {
141 id: Some(name),
142 values,
143 }] = document
144 else {
145 return Ok(None);
146 };
147 let [argument] = values.as_slice() else {
148 return Ok(None);
149 };
150 let operation = match name.as_str() {
151 "count" => Self::Count(parse_restriction(argument)?),
152 "each" => Self::Each(parse_restriction(argument)?),
153 "create" => {
154 let [source, target] = parse_numbers_for::<T, 2>(argument)?;
155 Self::Create { source, target }
156 }
157 "update" => {
158 let [index, source, target] = parse_numbers_for::<T, 3>(argument)?;
159 Self::Update {
160 index,
161 source,
162 target,
163 }
164 }
165 "delete" => Self::Delete(parse_number(argument)?),
166 "get-name" => Self::GetName(parse_number(argument)?),
167 "set-name" => match parts(argument) {
168 [index, LiNo::Ref(name)] => Self::SetName(parse_number(index)?, name.clone()),
169 _ => return Err(malformed_argument("set-name", argument)),
170 },
171 "get-by-name" => match argument {
172 LiNo::Ref(name) => Self::GetByName(name.clone()),
173 _ => return Err(malformed_argument("get-by-name", argument)),
174 },
175 "remove-name" => Self::RemoveName(parse_number(argument)?),
176 "subscribe" => Self::Subscribe(parse_restriction(argument)?),
177 "unsubscribe" => Self::Unsubscribe(parse_number(argument)?),
178 _ => return Ok(None),
179 };
180 Ok(Some(operation))
181 }
182
183 pub fn execute<S: NamedTypeLinks<T> + ?Sized>(
185 &self,
186 storage: &mut S,
187 ) -> anyhow::Result<LinoDocument> {
188 if let Some(limits) = storage.query_limits() {
189 match self {
190 Self::Count(parts) | Self::Each(parts) | Self::Subscribe(parts) => {
191 anyhow::ensure!(parts.len() <= 3, "expected at most three restriction parts")
192 }
193 Self::SetName(_, name) | Self::GetByName(name) => anyhow::ensure!(
194 name.len() <= limits.max_bytes,
195 "protocol byte limit exceeded"
196 ),
197 _ => {}
198 }
199 let addresses: Vec<T> = match self {
200 Self::Count(parts) | Self::Each(parts) | Self::Subscribe(parts) => {
201 parts.iter().flatten().copied().collect()
202 }
203 Self::Create { source, target } => vec![*source, *target],
204 Self::Update {
205 index,
206 source,
207 target,
208 } => vec![*index, *source, *target],
209 Self::Delete(index)
210 | Self::GetName(index)
211 | Self::SetName(index, _)
212 | Self::RemoveName(index)
213 | Self::Unsubscribe(index) => vec![*index],
214 Self::GetByName(_) => Vec::new(),
215 };
216 anyhow::ensure!(
217 addresses.iter().all(|value| value
218 .to_u128()
219 .is_some_and(|value| value <= limits.max_address)),
220 "protocol address out of range"
221 );
222 }
223 Ok(match self {
224 Self::Count(restriction) => {
225 let count = matching(storage, restriction).len();
226 vec![named("count", vec![LiNo::Ref(count.to_string())])]
227 }
228 Self::Each(restriction) => {
229 let links = matching(storage, restriction);
230 if let Some(limits) = storage.query_limits() {
231 anyhow::ensure!(
232 links.len() <= limits.max_results,
233 "protocol result limit exceeded"
234 );
235 }
236 links.iter().map(link_lino).collect()
237 }
238 Self::Create { source, target } => {
239 let created =
241 GenericLink::new(storage.try_create(*source, *target)?, *source, *target);
242 storage.save()?;
243 changes_document_for(&[(GenericLink::null(), created)])
244 }
245 Self::Update {
246 index,
247 source,
248 target,
249 } => {
250 let mut changes = Vec::new();
251 storage.update_observed(*index, *source, *target, &mut |before, after| {
252 changes.push((before, after))
253 })?;
254 storage.save()?;
255 changes_document_for(&simplify_generic_changes(changes))
256 }
257 Self::Delete(index) => {
258 let mut changes = Vec::new();
259 storage
260 .delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
261 storage.save()?;
262 changes_document_for(&simplify_generic_changes(changes))
263 }
264 Self::GetName(index) => match storage.get_name(*index)? {
265 Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
266 None => Vec::new(),
267 },
268 Self::SetName(index, name) => {
269 let link = storage.set_name(*index, name)?;
270 storage.save()?;
271 link_reply(Some(link))
272 }
273 Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
274 Self::RemoveName(index) => {
275 storage.remove_name(*index)?;
276 storage.save()?;
277 Vec::new()
278 }
279 Self::Subscribe(_) | Self::Unsubscribe(_) => {
280 anyhow::bail!("subscriptions belong to a connection to a links server")
281 }
282 })
283 }
284}
285
286pub fn matches<T: QueryAddress>(link: &GenericLink<T>, restriction: &[Part<T>]) -> bool {
289 let is = |part: Part<T>, value: T| part.is_none_or(|part| part == value);
290 match *restriction {
291 [] => true,
292 [index] => is(index, link.index),
293 [index, value] => {
294 is(index, link.index) && (is(value, link.source) || is(value, link.target))
295 }
296 [index, source, target] => {
297 is(index, link.index) && is(source, link.source) && is(target, link.target)
298 }
299 _ => false,
300 }
301}
302
303fn matching<T: QueryAddress, S: NamedTypeLinks<T> + ?Sized>(
304 storage: &mut S,
305 restriction: &[Part<T>],
306) -> Vec<GenericLink<T>> {
307 let mut links = match restriction.first() {
308 Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
309 _ => storage.all_links(),
310 };
311 links.retain(|link| matches(link, restriction));
312 links.sort_by_key(|link| link.index);
313 links
314}
315
316pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
318 match document {
319 [LiNo::Link {
320 id: Some(id),
321 values,
322 }] if id == "count" => match values.as_slice() {
323 [count] => parse_number(count),
324 _ => Err(malformed_reply("count", document)),
325 },
326 _ => Err(malformed_reply("count", document)),
327 }
328}
329
330pub fn parse_subscription(document: &[LiNo<String>]) -> ProtocolResult<u32> {
332 match document {
333 [LiNo::Link {
334 id: Some(id),
335 values,
336 }] if id == "subscription" => match values.as_slice() {
337 [subscription] => parse_number(subscription),
338 _ => Err(malformed_reply("subscription", document)),
339 },
340 _ => Err(malformed_reply("subscription", document)),
341 }
342}
343
344pub fn subscription_document(subscription: u32) -> LinoDocument {
346 vec![named("subscription", vec![number(subscription)])]
347}
348
349pub fn is_notification(document: &[LiNo<String>]) -> bool {
356 notification_number(document).is_some()
357}
358
359pub(super) fn notification_number(document: &[LiNo<String>]) -> Option<u32> {
360 match document.first()? {
361 LiNo::Link {
362 id: Some(id),
363 values,
364 } if id == "notify" => match values.as_slice() {
365 [LiNo::Ref(text)] if text.bytes().all(|byte| byte.is_ascii_digit()) => {
366 text.parse().ok()
367 }
368 _ => None,
369 },
370 _ => None,
371 }
372}
373
374pub fn notification_document(subscription: u32, changes: &[Change]) -> LinoDocument {
377 let mut document = vec![named("notify", vec![number(subscription)])];
378 document.extend(changes_document(changes));
379 document
380}
381
382pub fn parse_notification(document: &[LiNo<String>]) -> ProtocolResult<LinksNotification> {
384 let subscription =
385 notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
386 Ok(LinksNotification {
387 subscription,
388 changes: parse_changes(&document[1..])?,
389 })
390}
391
392pub fn parse_links_for<T: QueryAddress>(
394 document: &[LiNo<String>],
395) -> ProtocolResult<Vec<GenericLink<T>>> {
396 document.iter().map(parse_link).collect()
397}
398
399pub fn parse_changes_for<T: QueryAddress>(
401 document: &[LiNo<String>],
402) -> ProtocolResult<Vec<Change<T>>> {
403 document
404 .iter()
405 .map(|change| match parts(change) {
406 [before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
407 _ => Err(malformed_reply("change", document)),
408 })
409 .collect()
410}
411
412pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
414 match document {
415 [] => Ok(None),
416 [LiNo::Link {
417 id: Some(id),
418 values,
419 }] if id == "name" => match values.as_slice() {
420 [LiNo::Ref(name)] => Ok(Some(name.clone())),
421 _ => Err(malformed_reply("name", document)),
422 },
423 _ => Err(malformed_reply("name", document)),
424 }
425}
426
427pub fn parse_link_reply_for<T: QueryAddress>(
429 document: &[LiNo<String>],
430) -> ProtocolResult<Option<T>> {
431 match document {
432 [] => Ok(None),
433 [LiNo::Link {
434 id: Some(id),
435 values,
436 }] if id == "link" => match values.as_slice() {
437 [link] => parse_number(link).map(Some),
438 _ => Err(malformed_reply("link", document)),
439 },
440 _ => Err(malformed_reply("link", document)),
441 }
442}
443
444pub fn changes_document_for<T: QueryAddress>(changes: &[Change<T>]) -> LinoDocument {
446 changes
447 .iter()
448 .map(|(before, after)| group(vec![change_side(before), change_side(after)]))
449 .collect()
450}
451
452pub fn link_lino<T: QueryAddress>(link: &GenericLink<T>) -> LiNo<String> {
454 named(
455 &link.index.to_string(),
456 vec![number(link.source), number(link.target)],
457 )
458}
459
460fn link_reply<T: QueryAddress>(link: Option<T>) -> LinoDocument {
461 link.map(|link| vec![named("link", vec![number(link)])])
462 .unwrap_or_default()
463}
464
465fn change_side<T: QueryAddress>(link: &GenericLink<T>) -> LiNo<String> {
466 if link.is_null() {
467 group(Vec::new())
468 } else {
469 group(vec![link_lino(link)])
470 }
471}
472
473fn parse_change_side<T: QueryAddress>(side: &LiNo<String>) -> ProtocolResult<GenericLink<T>> {
474 match side {
475 LiNo::Link { id: None, values } if values.is_empty() => Ok(GenericLink::null()),
476 LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
477 link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
480 _ => Err(ProtocolError::malformed(format!(
481 "expected a change side, found {}",
482 format_link(side)
483 ))),
484 }
485}
486
487fn parse_link<T: QueryAddress>(link: &LiNo<String>) -> ProtocolResult<GenericLink<T>> {
488 match link {
489 LiNo::Link {
490 id: Some(index),
491 values,
492 } => match values.as_slice() {
493 [source, target] => Ok(GenericLink::new(
494 parse_text_number(index)?,
495 parse_number(source)?,
496 parse_number(target)?,
497 )),
498 _ => Err(ProtocolError::malformed(format!(
499 "expected (index: source target), found {}",
500 format_link(link)
501 ))),
502 },
503 _ => Err(ProtocolError::malformed(format!(
504 "expected (index: source target), found {}",
505 format_link(link)
506 ))),
507 }
508}
509
510pub(super) fn restriction_lino<T: QueryAddress>(restriction: &[Part<T>]) -> LiNo<String> {
511 group(
512 restriction
513 .iter()
514 .map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
515 .collect(),
516 )
517}
518
519pub(super) fn parse_restriction<T: QueryAddress>(
520 argument: &LiNo<String>,
521) -> ProtocolResult<Vec<Part<T>>> {
522 parse_restriction_of(argument, 3)
523}
524
525pub(super) fn parse_restriction_of<T: QueryAddress>(
526 argument: &LiNo<String>,
527 longest: usize,
528) -> ProtocolResult<Vec<Part<T>>> {
529 let parts = parts(argument);
530 if parts.len() > longest {
531 return Err(malformed_argument("restriction", argument));
532 }
533 parts
534 .iter()
535 .map(|part| match part {
536 LiNo::Ref(text) if text == ANY => Ok(None),
537 part => parse_number(part).map(Some),
538 })
539 .collect()
540}
541
542pub(super) fn numbers_lino<T: QueryAddress>(numbers: &[T]) -> LiNo<String> {
543 group(numbers.iter().copied().map(number).collect())
544}
545
546fn parse_numbers_for<T: QueryAddress, const N: usize>(
547 argument: &LiNo<String>,
548) -> ProtocolResult<[T; N]> {
549 let numbers = parts(argument)
550 .iter()
551 .map(parse_number)
552 .collect::<ProtocolResult<Vec<_>>>()?;
553 numbers
554 .try_into()
555 .map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
556}
557
558pub(super) fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
561 match argument {
562 LiNo::Link { id: None, values } => values,
563 reference => std::slice::from_ref(reference),
564 }
565}
566
567pub(super) fn parse_number<T: QueryAddress>(value: &LiNo<String>) -> ProtocolResult<T> {
568 match value {
569 LiNo::Ref(text) => parse_text_number(text),
570 _ => Err(ProtocolError::malformed(format!(
571 "expected a number, found {}",
572 format_link(value)
573 ))),
574 }
575}
576
577pub(super) fn parse_text_number<T: QueryAddress>(text: &str) -> ProtocolResult<T> {
578 text.parse()
579 .map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
580}
581
582pub(super) fn number<T: QueryAddress>(value: T) -> LiNo<String> {
583 LiNo::Ref(value.to_string())
584}
585
586pub(super) fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
587 LiNo::Link {
588 id: Some(id.to_string()),
589 values,
590 }
591}
592
593pub(super) fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
594 LiNo::Link { id: None, values }
595}
596
597pub(super) fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
598 ProtocolError::malformed(format!(
599 "expected {expected}, found {}",
600 format_link(argument)
601 ))
602}
603
604pub(super) fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
605 ProtocolError::malformed(format!(
606 "expected a {expected} reply, found {}",
607 format_document(document)
608 ))
609}
610
611pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
613 parse_links_for(document)
614}
615
616pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
618 parse_changes_for(document)
619}
620
621pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
623 parse_link_reply_for(document)
624}
625
626pub fn changes_document(changes: &[Change]) -> LinoDocument {
628 changes_document_for(changes)
629}
630
631pub(super) fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
632 parse_numbers_for::<u32, N>(argument)
633}