1use super::error::{ProtocolError, ProtocolResult};
38use super::links_operations::{
39 group, malformed_argument, malformed_reply, named, notification_number, number, numbers_lino,
40 parse_number, parse_numbers, parse_restriction_of, parse_text_number, parts, restriction_lino,
41 LinksOperation, Part,
42};
43use super::protocols::MessageFormat;
44use super::server::{error_document, reference_name};
45use crate::triplets::{process_triplets_query, Triplet, TripletChange, TripletQuery, Triplets};
46use links_notation::binary::{format_document, format_link, LinoDocument};
47use links_notation::LiNo;
48
49#[derive(Clone, Debug, PartialEq, Eq)]
51pub enum TripletsOperation {
52 Count(Vec<Part>),
54 Each(Vec<Part>),
56 Create { type_id: u32, from: u32, to: u32 },
58 Update {
60 index: u32,
61 type_id: u32,
62 from: u32,
63 to: u32,
64 },
65 Delete(u32),
67 Subscribe(Vec<Part>),
71}
72
73#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct TripletsNotification {
78 pub subscription: u32,
80 pub changes: Vec<TripletChange>,
82}
83
84impl TripletsOperation {
85 pub fn to_document(&self) -> LinoDocument {
87 let (name, argument) = match self {
88 Self::Count(restriction) => ("count", restriction_lino(restriction)),
89 Self::Each(restriction) => ("each", restriction_lino(restriction)),
90 Self::Create { type_id, from, to } => ("create", numbers_lino(&[*type_id, *from, *to])),
91 Self::Update {
92 index,
93 type_id,
94 from,
95 to,
96 } => ("update", numbers_lino(&[*index, *type_id, *from, *to])),
97 Self::Delete(index) => ("delete", number(*index)),
98 Self::Subscribe(restriction) => ("subscribe", restriction_lino(restriction)),
99 };
100 vec![named(name, vec![argument])]
101 }
102
103 pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
106 let [LiNo::Link {
107 id: Some(name),
108 values,
109 }] = document
110 else {
111 return Ok(None);
112 };
113 let [argument] = values.as_slice() else {
114 return Ok(None);
115 };
116 let operation = match name.as_str() {
117 "count" => Self::Count(parse_restriction_of(argument, 4)?),
118 "each" => Self::Each(parse_restriction_of(argument, 4)?),
119 "create" => {
120 let [type_id, from, to] = parse_numbers::<3>(argument)?;
121 Self::Create { type_id, from, to }
122 }
123 "update" => {
124 let [index, type_id, from, to] = parse_numbers::<4>(argument)?;
125 Self::Update {
126 index,
127 type_id,
128 from,
129 to,
130 }
131 }
132 "delete" => Self::Delete(parse_number(argument)?),
133 "subscribe" => Self::Subscribe(parse_restriction_of(argument, 4)?),
134 _ => return Ok(None),
135 };
136 Ok(Some(operation))
137 }
138
139 pub fn execute<T: Triplets + ?Sized>(&self, triplets: &mut T) -> anyhow::Result<LinoDocument> {
141 Ok(match self {
142 Self::Count(restriction) => {
143 let count = matching(triplets, restriction).len();
144 vec![named("count", vec![number(count as u32)])]
145 }
146 Self::Each(restriction) => matching(triplets, restriction)
147 .iter()
148 .map(triplet_lino)
149 .collect(),
150 Self::Create { type_id, from, to } => {
151 let created = if (*type_id, *from, *to) == (0, 0, 0) {
152 let index = triplets.create_triplet_point()?;
153 Triplet::new(index, index, 0, 0)
154 } else {
155 let index = triplets.create_triplet(*type_id, *from, *to)?;
156 Triplet::new(index, *type_id, *from, *to)
157 };
158 triplets.save()?;
159 triplet_changes_document(&[TripletChange {
160 before: None,
161 after: Some(created),
162 }])
163 }
164 Self::Update {
165 index,
166 type_id,
167 from,
168 to,
169 } => {
170 let before = triplets.update_triplet(*index, *type_id, *from, *to)?;
171 triplets.save()?;
172 triplet_changes_document(&[TripletChange {
173 before: Some(before),
174 after: Some(Triplet::new(*index, *type_id, *from, *to)),
175 }])
176 }
177 Self::Delete(index) => {
178 let deleted = triplets.delete_triplet(*index)?;
179 triplets.save()?;
180 let changes: Vec<TripletChange> = deleted
181 .into_iter()
182 .map(|triplet| TripletChange {
183 before: Some(triplet),
184 after: None,
185 })
186 .collect();
187 triplet_changes_document(&changes)
188 }
189 Self::Subscribe(_) => {
190 anyhow::bail!("subscriptions belong to a connection to a links server")
191 }
192 })
193 }
194}
195
196pub fn triplet_query(restriction: &[Part]) -> TripletQuery {
198 let part = |at: usize| restriction.get(at).copied().flatten();
199 TripletQuery::new(part(0), part(1), part(2), part(3))
200}
201
202pub fn restriction_of_query(query: TripletQuery) -> Vec<Part> {
204 vec![query.index, query.type_id, query.from, query.to]
205}
206
207pub fn matches_triplet(triplet: &Triplet, restriction: &[Part]) -> bool {
209 restriction.len() <= 4 && triplet_query(restriction).matches(triplet)
210}
211
212fn matching<T: Triplets + ?Sized>(triplets: &mut T, restriction: &[Part]) -> Vec<Triplet> {
213 triplets.each_triplet(triplet_query(restriction))
214}
215
216pub fn execute_triplets_request<T: Triplets + ?Sized>(
222 triplets: &mut T,
223 document: &[LiNo<String>],
224) -> LinoDocument {
225 execute_observed_triplets_request(triplets, document, &mut Vec::new())
226}
227
228pub(super) fn execute_observed_triplets_request<T: Triplets + ?Sized>(
231 triplets: &mut T,
232 document: &[LiNo<String>],
233 changed: &mut Vec<TripletChange>,
234) -> LinoDocument {
235 match try_execute_triplets_request(triplets, document, changed) {
236 Ok(reply) => reply,
237 Err(error) => error_document(&format!("{error:#}")),
238 }
239}
240
241fn try_execute_triplets_request<T: Triplets + ?Sized>(
242 triplets: &mut T,
243 document: &[LiNo<String>],
244 changed: &mut Vec<TripletChange>,
245) -> anyhow::Result<LinoDocument> {
246 if let Some(operation) = TripletsOperation::from_document(document)? {
247 let reply = operation.execute(triplets)?;
248 if matches!(
249 operation,
250 TripletsOperation::Create { .. }
251 | TripletsOperation::Update { .. }
252 | TripletsOperation::Delete(_)
253 ) {
254 changed.extend(
255 parse_triplet_changes(&reply)?
256 .into_iter()
257 .filter(|change| change.before != change.after),
258 );
259 }
260 return Ok(reply);
261 }
262 if let Some(operation) = LinksOperation::from_document(document)? {
263 return operation.execute(triplets);
264 }
265 if document.is_empty() {
266 return triplets
267 .each_triplet(TripletQuery::any())
268 .iter()
269 .map(|triplet| named_triplet_lino(triplets, triplet))
270 .collect();
271 }
272 let changes = process_triplets_query(triplets, &format_document(document))?;
273 let writes = changes
274 .iter()
275 .filter(|change| change.before != change.after);
276 let before = changed.len();
277 changed.extend(writes.copied());
278 if changed.len() != before {
279 triplets.save()?;
280 }
281 changes
282 .iter()
283 .map(|change| {
284 Ok(group(vec![
285 named_side(triplets, change.before.as_ref())?,
286 named_side(triplets, change.after.as_ref())?,
287 ]))
288 })
289 .collect()
290}
291
292fn named_triplet_lino<T: Triplets + ?Sized>(
294 triplets: &mut T,
295 triplet: &Triplet,
296) -> anyhow::Result<LiNo<String>> {
297 let mut reference = |id: u32| -> anyhow::Result<String> { reference_name(triplets, id) };
298 Ok(LiNo::Link {
299 id: Some(reference(triplet.index)?),
300 values: vec![
301 LiNo::Ref(reference(triplet.type_id)?),
302 LiNo::Ref(reference(triplet.from)?),
303 LiNo::Ref(reference(triplet.to)?),
304 ],
305 })
306}
307
308fn named_side<T: Triplets + ?Sized>(
309 triplets: &mut T,
310 triplet: Option<&Triplet>,
311) -> anyhow::Result<LiNo<String>> {
312 Ok(group(match triplet {
313 Some(triplet) => vec![named_triplet_lino(triplets, triplet)?],
314 None => Vec::new(),
315 }))
316}
317
318pub fn triplet_lino(triplet: &Triplet) -> LiNo<String> {
320 named(
321 &triplet.index.to_string(),
322 vec![
323 number(triplet.type_id),
324 number(triplet.from),
325 number(triplet.to),
326 ],
327 )
328}
329
330fn side_lino(triplet: Option<&Triplet>) -> LiNo<String> {
331 group(triplet.map(triplet_lino).into_iter().collect())
332}
333
334pub fn triplet_changes_document(changes: &[TripletChange]) -> LinoDocument {
336 changes
337 .iter()
338 .map(|change| {
339 group(vec![
340 side_lino(change.before.as_ref()),
341 side_lino(change.after.as_ref()),
342 ])
343 })
344 .collect()
345}
346
347pub fn triplet_notification_document(subscription: u32, changes: &[TripletChange]) -> LinoDocument {
349 let mut document = vec![named("notify", vec![number(subscription)])];
350 document.extend(triplet_changes_document(changes));
351 document
352}
353
354pub fn parse_triplet_notification(
356 document: &[LiNo<String>],
357) -> ProtocolResult<TripletsNotification> {
358 let subscription =
359 notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
360 Ok(TripletsNotification {
361 subscription,
362 changes: parse_triplet_changes(&document[1..])?,
363 })
364}
365
366pub fn parse_triplets(document: &[LiNo<String>]) -> ProtocolResult<Vec<Triplet>> {
368 document.iter().map(parse_triplet).collect()
369}
370
371pub fn parse_triplet_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<TripletChange>> {
373 document
374 .iter()
375 .map(|change| match parts(change) {
376 [before, after] => Ok(TripletChange {
377 before: parse_side(before)?,
378 after: parse_side(after)?,
379 }),
380 _ => Err(malformed_reply("change", document)),
381 })
382 .collect()
383}
384
385fn parse_side(side: &LiNo<String>) -> ProtocolResult<Option<Triplet>> {
386 match side {
387 LiNo::Link { id: None, values } if values.is_empty() => Ok(None),
388 LiNo::Link { id: None, values } if values.len() == 1 => parse_triplet(&values[0]).map(Some),
389 link @ LiNo::Link { id: Some(_), .. } => parse_triplet(link).map(Some),
392 _ => Err(malformed_argument("a change side", side)),
393 }
394}
395
396pub fn parse_triplet(link: &LiNo<String>) -> ProtocolResult<Triplet> {
398 let malformed = || {
399 ProtocolError::malformed(format!(
400 "expected (index: type from to), found {}",
401 format_link(link)
402 ))
403 };
404 let LiNo::Link {
405 id: Some(index),
406 values,
407 } = link
408 else {
409 return Err(malformed());
410 };
411 let values: &[LiNo<String>] = match values.as_slice() {
412 [LiNo::Link { id: None, values }] => values,
413 values => values,
414 };
415 let [type_id, from, to] = values else {
416 return Err(malformed());
417 };
418 Ok(Triplet::new(
419 parse_text_number(index)?,
420 parse_number(type_id)?,
421 parse_number(from)?,
422 parse_number(to)?,
423 ))
424}
425
426pub fn pack_triplets(document: LinoDocument, format: MessageFormat) -> LinoDocument {
435 match format {
436 MessageFormat::Binary(options)
437 if options.arity.contains(3) && !options.arity.contains(5) =>
438 {
439 document.into_iter().map(pack_link).collect()
440 }
441 _ => document,
442 }
443}
444
445fn pack_link(link: LiNo<String>) -> LiNo<String> {
446 match link {
447 LiNo::Link { id: None, values } => group(values.into_iter().map(pack_link).collect()),
448 LiNo::Link {
449 id: Some(id),
450 values,
451 } if values.len() == 3 => LiNo::Link {
452 id: Some(id),
453 values: vec![group(values)],
454 },
455 link => link,
456 }
457}
458
459pub fn canonical_triplets(document: LinoDocument) -> LinoDocument {
462 document.into_iter().map(unpack_link).collect()
463}
464
465fn unpack_link(link: LiNo<String>) -> LiNo<String> {
466 match link {
467 LiNo::Link { id: None, values } => group(values.into_iter().map(unpack_link).collect()),
468 LiNo::Link {
469 id: Some(id),
470 mut values,
471 } if matches!(
472 values.as_slice(),
473 [LiNo::Link { id: None, values }] if values.len() == 3
474 ) =>
475 {
476 let Some(LiNo::Link { values, .. }) = values.pop() else {
477 unreachable!("the guard holds one unnamed link");
478 };
479 LiNo::Link {
480 id: Some(id),
481 values,
482 }
483 }
484 link => link,
485 }
486}