1use super::error::{ProtocolError, ProtocolResult};
43use crate::changes_simplifier::simplify_changes;
44use crate::link::Link;
45use crate::named_type_links::NamedTypeLinks;
46use links_notation::binary::{format_document, format_link, LinoDocument};
47use links_notation::LiNo;
48
49pub const ANY: &str = "*";
51
52pub type Part = Option<u32>;
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum LinksOperation {
58 Count(Vec<Part>),
60 Each(Vec<Part>),
62 Create { source: u32, target: u32 },
64 Update {
67 index: u32,
68 source: u32,
69 target: u32,
70 },
71 Delete(u32),
73 GetName(u32),
75 SetName(u32, String),
77 GetByName(String),
79 RemoveName(u32),
81 Subscribe(Vec<Part>),
88 Unsubscribe(u32),
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct LinksNotification {
102 pub subscription: u32,
104 pub changes: Vec<Change>,
106}
107
108pub type Change = (Link, Link);
110
111impl LinksOperation {
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::<2>(argument)?;
155 Self::Create { source, target }
156 }
157 "update" => {
158 let [index, source, target] = parse_numbers::<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 + ?Sized>(
185 &self,
186 storage: &mut S,
187 ) -> anyhow::Result<LinoDocument> {
188 Ok(match self {
189 Self::Count(restriction) => {
190 let count = matching(storage, restriction).len();
191 vec![named("count", vec![LiNo::Ref(count.to_string())])]
192 }
193 Self::Each(restriction) => matching(storage, restriction)
194 .iter()
195 .map(link_lino)
196 .collect(),
197 Self::Create { source, target } => {
198 let created = Link::new(storage.create(*source, *target), *source, *target);
200 storage.save()?;
201 changes_document(&[(Link::null(), created)])
202 }
203 Self::Update {
204 index,
205 source,
206 target,
207 } => {
208 let mut changes = Vec::new();
209 storage.update_observed(*index, *source, *target, &mut |before, after| {
210 changes.push((before, after))
211 })?;
212 storage.save()?;
213 changes_document(&simplify_changes(changes))
214 }
215 Self::Delete(index) => {
216 let mut changes = Vec::new();
217 storage
218 .delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
219 storage.save()?;
220 changes_document(&simplify_changes(changes))
221 }
222 Self::GetName(index) => match storage.get_name(*index)? {
223 Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
224 None => Vec::new(),
225 },
226 Self::SetName(index, name) => {
227 let link = storage.set_name(*index, name)?;
228 storage.save()?;
229 link_reply(Some(link))
230 }
231 Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
232 Self::RemoveName(index) => {
233 storage.remove_name(*index)?;
234 storage.save()?;
235 Vec::new()
236 }
237 Self::Subscribe(_) | Self::Unsubscribe(_) => {
238 anyhow::bail!("subscriptions belong to a connection to a links server")
239 }
240 })
241 }
242}
243
244pub fn matches(link: &Link, restriction: &[Part]) -> bool {
247 let is = |part: Part, value: u32| part.is_none_or(|part| part == value);
248 match *restriction {
249 [] => true,
250 [index] => is(index, link.index),
251 [index, value] => {
252 is(index, link.index) && (is(value, link.source) || is(value, link.target))
253 }
254 [index, source, target] => {
255 is(index, link.index) && is(source, link.source) && is(target, link.target)
256 }
257 _ => false,
258 }
259}
260
261fn matching<S: NamedTypeLinks + ?Sized>(storage: &mut S, restriction: &[Part]) -> Vec<Link> {
262 let mut links = match restriction.first() {
263 Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
264 _ => storage.all_links(),
265 };
266 links.retain(|link| matches(link, restriction));
267 links.sort_by_key(|link| link.index);
268 links
269}
270
271pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
273 match document {
274 [LiNo::Link {
275 id: Some(id),
276 values,
277 }] if id == "count" => match values.as_slice() {
278 [count] => parse_number(count),
279 _ => Err(malformed_reply("count", document)),
280 },
281 _ => Err(malformed_reply("count", document)),
282 }
283}
284
285pub fn parse_subscription(document: &[LiNo<String>]) -> ProtocolResult<u32> {
287 match document {
288 [LiNo::Link {
289 id: Some(id),
290 values,
291 }] if id == "subscription" => match values.as_slice() {
292 [subscription] => parse_number(subscription),
293 _ => Err(malformed_reply("subscription", document)),
294 },
295 _ => Err(malformed_reply("subscription", document)),
296 }
297}
298
299pub fn subscription_document(subscription: u32) -> LinoDocument {
301 vec![named("subscription", vec![number(subscription)])]
302}
303
304pub fn is_notification(document: &[LiNo<String>]) -> bool {
311 notification_number(document).is_some()
312}
313
314fn notification_number(document: &[LiNo<String>]) -> Option<u32> {
315 match document.first()? {
316 LiNo::Link {
317 id: Some(id),
318 values,
319 } if id == "notify" => match values.as_slice() {
320 [LiNo::Ref(text)] if text.bytes().all(|byte| byte.is_ascii_digit()) => {
321 text.parse().ok()
322 }
323 _ => None,
324 },
325 _ => None,
326 }
327}
328
329pub fn notification_document(subscription: u32, changes: &[Change]) -> LinoDocument {
332 let mut document = vec![named("notify", vec![number(subscription)])];
333 document.extend(changes_document(changes));
334 document
335}
336
337pub fn parse_notification(document: &[LiNo<String>]) -> ProtocolResult<LinksNotification> {
339 let subscription =
340 notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
341 Ok(LinksNotification {
342 subscription,
343 changes: parse_changes(&document[1..])?,
344 })
345}
346
347pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
349 document.iter().map(parse_link).collect()
350}
351
352pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
354 document
355 .iter()
356 .map(|change| match parts(change) {
357 [before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
358 _ => Err(malformed_reply("change", document)),
359 })
360 .collect()
361}
362
363pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
365 match document {
366 [] => Ok(None),
367 [LiNo::Link {
368 id: Some(id),
369 values,
370 }] if id == "name" => match values.as_slice() {
371 [LiNo::Ref(name)] => Ok(Some(name.clone())),
372 _ => Err(malformed_reply("name", document)),
373 },
374 _ => Err(malformed_reply("name", document)),
375 }
376}
377
378pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
380 match document {
381 [] => Ok(None),
382 [LiNo::Link {
383 id: Some(id),
384 values,
385 }] if id == "link" => match values.as_slice() {
386 [link] => parse_number(link).map(Some),
387 _ => Err(malformed_reply("link", document)),
388 },
389 _ => Err(malformed_reply("link", document)),
390 }
391}
392
393pub fn changes_document(changes: &[Change]) -> LinoDocument {
395 changes
396 .iter()
397 .map(|(before, after)| group(vec![change_side(before), change_side(after)]))
398 .collect()
399}
400
401pub fn link_lino(link: &Link) -> LiNo<String> {
403 named(
404 &link.index.to_string(),
405 vec![number(link.source), number(link.target)],
406 )
407}
408
409fn link_reply(link: Option<u32>) -> LinoDocument {
410 link.map(|link| vec![named("link", vec![number(link)])])
411 .unwrap_or_default()
412}
413
414fn change_side(link: &Link) -> LiNo<String> {
415 if link.is_null() {
416 group(Vec::new())
417 } else {
418 group(vec![link_lino(link)])
419 }
420}
421
422fn parse_change_side(side: &LiNo<String>) -> ProtocolResult<Link> {
423 match side {
424 LiNo::Link { id: None, values } if values.is_empty() => Ok(Link::null()),
425 LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
426 link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
429 _ => Err(ProtocolError::malformed(format!(
430 "expected a change side, found {}",
431 format_link(side)
432 ))),
433 }
434}
435
436fn parse_link(link: &LiNo<String>) -> ProtocolResult<Link> {
437 match link {
438 LiNo::Link {
439 id: Some(index),
440 values,
441 } => match values.as_slice() {
442 [source, target] => Ok(Link::new(
443 parse_text_number(index)?,
444 parse_number(source)?,
445 parse_number(target)?,
446 )),
447 _ => Err(ProtocolError::malformed(format!(
448 "expected (index: source target), found {}",
449 format_link(link)
450 ))),
451 },
452 _ => Err(ProtocolError::malformed(format!(
453 "expected (index: source target), found {}",
454 format_link(link)
455 ))),
456 }
457}
458
459fn restriction_lino(restriction: &[Part]) -> LiNo<String> {
460 group(
461 restriction
462 .iter()
463 .map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
464 .collect(),
465 )
466}
467
468fn parse_restriction(argument: &LiNo<String>) -> ProtocolResult<Vec<Part>> {
469 let parts = parts(argument);
470 if parts.len() > 3 {
471 return Err(malformed_argument("restriction", argument));
472 }
473 parts
474 .iter()
475 .map(|part| match part {
476 LiNo::Ref(text) if text == ANY => Ok(None),
477 part => parse_number(part).map(Some),
478 })
479 .collect()
480}
481
482fn numbers_lino(numbers: &[u32]) -> LiNo<String> {
483 group(numbers.iter().copied().map(number).collect())
484}
485
486fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
487 let numbers = parts(argument)
488 .iter()
489 .map(parse_number)
490 .collect::<ProtocolResult<Vec<_>>>()?;
491 numbers
492 .try_into()
493 .map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
494}
495
496fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
499 match argument {
500 LiNo::Link { id: None, values } => values,
501 reference => std::slice::from_ref(reference),
502 }
503}
504
505fn parse_number(value: &LiNo<String>) -> ProtocolResult<u32> {
506 match value {
507 LiNo::Ref(text) => parse_text_number(text),
508 _ => Err(ProtocolError::malformed(format!(
509 "expected a number, found {}",
510 format_link(value)
511 ))),
512 }
513}
514
515fn parse_text_number(text: &str) -> ProtocolResult<u32> {
516 text.parse()
517 .map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
518}
519
520fn number(value: u32) -> LiNo<String> {
521 LiNo::Ref(value.to_string())
522}
523
524fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
525 LiNo::Link {
526 id: Some(id.to_string()),
527 values,
528 }
529}
530
531fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
532 LiNo::Link { id: None, values }
533}
534
535fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
536 ProtocolError::malformed(format!(
537 "expected {expected}, found {}",
538 format_link(argument)
539 ))
540}
541
542fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
543 ProtocolError::malformed(format!(
544 "expected a {expected} reply, found {}",
545 format_document(document)
546 ))
547}