1use std::collections::{BTreeMap, BTreeSet};
6use std::sync::OnceLock;
7
8use serde_json::{Value, json};
9
10use crate::resource_description_rules::{
11 accept_resource_description_identifier, accept_resource_description_language,
12 accept_resource_description_unicode, same_resource_description_term,
13};
14use crate::{LinkFlags, LinkId, LinkMetadata, LinkNetwork, LinkType, read_structured_data_lino};
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct ResourceDescriptionLinks {
19 pub network: LinkNetwork,
21 pub root: LinkId,
23}
24
25fn schema() -> &'static Value {
26 static SCHEMA: OnceLock<Value> = OnceLock::new();
27 SCHEMA.get_or_init(|| {
28 read_structured_data_lino(include_str!("data/resource-description-schema.lino"))
29 .expect("the packaged resource description schema is valid")
30 })
31}
32
33fn fail(message: &str) -> String {
34 format!("resource description graph: {message}")
35}
36
37fn units(text: &str) -> Vec<f64> {
38 text.encode_utf16().map(f64::from).collect()
39}
40
41fn bounded_text(value: &Value) -> Result<&str, String> {
42 let text = value
43 .as_str()
44 .ok_or_else(|| fail("a bounded Unicode scalar string is required"))?;
45 let code_units = units(text);
46 if code_units.len() > 65_536 || !accept_resource_description_unicode(&code_units) {
47 return Err(fail("a bounded Unicode scalar string is required"));
48 }
49 Ok(text)
50}
51
52fn identifier(text: &str) -> Result<&str, String> {
53 if !accept_resource_description_identifier(&units(text)) {
54 return Err(fail(
55 "an absolute identifier is malformed or uses an unsupported bracketed address",
56 ));
57 }
58 Ok(text)
59}
60
61fn normalized_term(input: &Value, source: Option<&str>) -> Result<Value, String> {
62 let record = input
63 .as_object()
64 .ok_or_else(|| fail("a term must be a data record"))?;
65 let kind = input["kind"].as_str().unwrap_or("");
66 let fields: &[&str] = match kind {
67 "identifier" => &["kind", "value"],
68 "blank" => &["kind", "value", "sourceIdentifier"],
69 "literal" => &["kind", "value", "datatype", "language"],
70 _ => return Err(fail("a term has an unknown field")),
71 };
72 if record.keys().any(|field| !fields.contains(&field.as_str())) {
73 return Err(fail("a term has an unknown field"));
74 }
75 let lexical = bounded_text(&input["value"])?;
76 if kind == "identifier" {
77 return Ok(json!({"kind":kind, "value":identifier(lexical)?}));
78 }
79 if kind == "blank" {
80 let default = source.map_or(Value::Null, |text| Value::String(text.to_owned()));
81 let scope = bounded_text(
82 input
83 .get("sourceIdentifier")
84 .filter(|value| !value.is_null())
85 .unwrap_or(&default),
86 )?;
87 if lexical.is_empty() || scope.is_empty() {
88 return Err(fail(
89 "blank node identity needs a label and nonempty explicit source scope",
90 ));
91 }
92 return Ok(json!({"kind":kind, "value":lexical, "sourceIdentifier":scope}));
93 }
94 let language = input
95 .get("language")
96 .map(bounded_text)
97 .transpose()?
98 .unwrap_or("")
99 .to_lowercase();
100 let datatype = input
101 .get("datatype")
102 .filter(|value| !value.is_null())
103 .map(bounded_text)
104 .transpose()?
105 .unwrap_or_else(|| {
106 schema()[if language.is_empty() {
107 "stringDatatype"
108 } else {
109 "languageDatatype"
110 }]
111 .as_str()
112 .unwrap()
113 });
114 identifier(datatype)?;
115 if language.is_empty() {
116 if datatype == schema()["languageDatatype"] {
117 return Err(fail("a language string requires a nonempty language tag"));
118 }
119 } else if datatype != schema()["languageDatatype"]
120 || !accept_resource_description_language(
121 &units(&language),
122 schema()["grandfatheredLanguages"]
123 .as_array()
124 .unwrap()
125 .iter()
126 .any(|value| value == &language),
127 )
128 {
129 return Err(fail("a language tag or its datatype is invalid"));
130 }
131 Ok(json!({"kind":kind, "value":lexical, "datatype":datatype, "language":language}))
132}
133
134fn identity_parts(term: &Value) -> Vec<String> {
135 let fields: &[&str] = match term["kind"].as_str().unwrap() {
136 "identifier" => &["value"],
137 "blank" => &["sourceIdentifier", "value"],
138 _ => &["value", "datatype", "language"],
139 };
140 fields
141 .iter()
142 .map(|field| term[field].as_str().unwrap().to_owned())
143 .collect()
144}
145
146fn framed(text: &str) -> String {
147 format!("{}:{text}", text.encode_utf16().count())
148}
149
150fn identity(term: &Value) -> String {
151 std::iter::once(term["kind"].as_str().unwrap().to_owned())
152 .chain(identity_parts(term))
153 .map(|part| framed(&part))
154 .collect()
155}
156
157fn statement_identity(triple: &[Value]) -> String {
158 triple.iter().map(|term| framed(&identity(term))).collect()
159}
160
161fn same(left: &Value, right: &Value) -> bool {
162 same_resource_description_term(
163 left["kind"].as_str().unwrap(),
164 &identity_parts(left),
165 right["kind"].as_str().unwrap(),
166 &identity_parts(right),
167 )
168}
169
170fn check_positions(triple: &[Value]) -> Result<(), String> {
171 for (index, role) in ["subject", "predicate", "object"].iter().enumerate() {
172 if !schema()["positions"][role]
173 .as_array()
174 .unwrap()
175 .contains(&triple[index]["kind"])
176 {
177 return Err(fail("a term cannot occupy its statement position"));
178 }
179 }
180 Ok(())
181}
182
183struct Writer {
184 network: LinkNetwork,
185 terms: BTreeMap<String, LinkId>,
186 statements: BTreeMap<Vec<u16>, LinkId>,
187 occurrences: Vec<LinkId>,
188 sources: Vec<LinkId>,
189 witnesses: Vec<LinkId>,
190 model: LinkId,
191}
192
193impl Writer {
194 fn new() -> Result<Self, String> {
195 let mut output = Self {
196 network: LinkNetwork::new(),
197 terms: BTreeMap::new(),
198 statements: BTreeMap::new(),
199 occurrences: Vec::new(),
200 sources: Vec::new(),
201 witnesses: Vec::new(),
202 model: LinkId::from_u64(0),
203 };
204 let premise = output.text(schema()["specification"].as_str().unwrap())?;
205 output.model = output.node("model", &[premise], schema()["model"].as_str())?;
206 Ok(output)
207 }
208
209 fn append(&mut self, references: &[LinkId], data: LinkMetadata) -> Result<LinkId, String> {
210 if self.network.len() >= 100_000 {
211 return Err(fail("the output structural node limit is exceeded"));
212 }
213 Ok(self.network.insert_dynamic_link(references, data))
214 }
215
216 fn node(
217 &mut self,
218 kind: &str,
219 references: &[LinkId],
220 definition: Option<&str>,
221 ) -> Result<LinkId, String> {
222 let mut data = LinkMetadata::new()
223 .with_link_type(LinkType::Semantic)
224 .with_named(true)
225 .with_language(schema()["language"].as_str().unwrap())
226 .with_term(schema()["terms"][kind].as_str().unwrap());
227 if let Some(text) = definition {
228 data = data.with_definition(text);
229 }
230 self.append(references, data)
231 }
232
233 fn text(&mut self, text: &str) -> Result<LinkId, String> {
234 self.node("text", &[], Some(text))
235 }
236
237 fn term(&mut self, term: &Value) -> Result<LinkId, String> {
238 let signature = identity(term);
239 if let Some(id) = self.terms.get(&signature) {
240 return Ok(*id);
241 }
242 let kind = term["kind"].as_str().unwrap();
243 let references = match kind {
244 "identifier" => vec![self.text(term["value"].as_str().unwrap())?],
245 "blank" => vec![
246 self.text(term["sourceIdentifier"].as_str().unwrap())?,
247 self.text(term["value"].as_str().unwrap())?,
248 ],
249 _ => vec![
250 self.text(term["value"].as_str().unwrap())?,
251 self.term(&json!({"kind":"identifier","value":term["datatype"]}))?,
252 self.text(term["language"].as_str().unwrap())?,
253 ],
254 };
255 let id = self.node(kind, &references, None)?;
256 self.terms.insert(signature, id);
257 Ok(id)
258 }
259
260 fn statement(&mut self, triple: &[Value]) -> Result<LinkId, String> {
261 let signature: Vec<u16> = statement_identity(triple).encode_utf16().collect();
262 if let Some(id) = self.statements.get(&signature) {
263 return Ok(*id);
264 }
265 let references = triple
266 .iter()
267 .map(|term| self.term(term))
268 .collect::<Result<Vec<_>, _>>()?;
269 let id = self.node("statement", &references, None)?;
270 self.statements.insert(signature, id);
271 Ok(id)
272 }
273
274 fn occurrence(
275 &mut self,
276 triple: &[Value],
277 source: &str,
278 position: u64,
279 language: &str,
280 ) -> Result<(), String> {
281 let statement = self.statement(triple)?;
282 let scope = self.text(source)?;
283 let position = self.node("position", &[], Some(&position.to_string()))?;
284 let language = self.text(language)?;
285 let id = self.node("occurrence", &[statement, scope, position, language], None)?;
286 self.occurrences.push(id);
287 Ok(())
288 }
289
290 fn finish(mut self) -> Result<ResourceDescriptionLinks, String> {
291 let ids = self.statements.values().copied().collect::<Vec<_>>();
292 let statements = self.node("sequence", &ids, None)?;
293 let occurrences = self.node("sequence", &self.occurrences.clone(), None)?;
294 let sources = self.node("sequence", &self.sources.clone(), None)?;
295 let witnesses = self.node("sequence", &self.witnesses.clone(), None)?;
296 let root = self.node(
297 "root",
298 &[self.model, statements, occurrences, sources, witnesses],
299 Some("1"),
300 )?;
301 Ok(ResourceDescriptionLinks {
302 network: self.network,
303 root,
304 })
305 }
306}
307
308pub fn import_resource_description_graph(
313 triples: &Value,
314 source_identifier: &str,
315) -> Result<ResourceDescriptionLinks, String> {
316 bounded_text(&Value::String(source_identifier.to_owned()))?;
317 let statements = triples
318 .as_array()
319 .ok_or_else(|| fail("a bounded graph is required"))?;
320 if source_identifier.is_empty() || statements.len() > 10_000 {
321 return Err(fail(
322 "a bounded graph and a nonempty source identifier are required",
323 ));
324 }
325 let mut output = Writer::new()?;
326 for (position, input) in statements.iter().enumerate() {
327 let fields = input
328 .as_array()
329 .filter(|values| values.len() == 3)
330 .ok_or_else(|| fail("a statement needs exactly three terms"))?;
331 let triple = fields
332 .iter()
333 .map(|term| normalized_term(term, Some(source_identifier)))
334 .collect::<Result<Vec<_>, _>>()?;
335 check_positions(&triple)?;
336 let language = if input[2]["kind"] == "literal" {
337 input[2]
338 .get("language")
339 .map(bounded_text)
340 .transpose()?
341 .unwrap_or("")
342 } else {
343 ""
344 };
345 output.occurrence(
346 &triple,
347 source_identifier,
348 u64::try_from(position).unwrap(),
349 language,
350 )?;
351 }
352 let result = output.finish()?;
353 decode_resource_description_graph(&result.network, result.root)?;
354 Ok(result)
355}
356
357#[derive(Clone)]
358struct Graph {
359 triples: Vec<Vec<Value>>,
360 occurrences: Vec<Value>,
361 statement_ids: Vec<LinkId>,
362}
363
364struct Reader<'a> {
365 network: &'a LinkNetwork,
366 node_limit: usize,
367 visited: BTreeSet<LinkId>,
368 active: BTreeSet<LinkId>,
369 fields: BTreeSet<LinkId>,
370 terms: BTreeMap<LinkId, Value>,
371 roots: BTreeMap<LinkId, Graph>,
372}
373
374impl<'a> Reader<'a> {
375 fn new(network: &'a LinkNetwork, node_limit: usize) -> Self {
376 Self {
377 network,
378 node_limit,
379 visited: BTreeSet::new(),
380 active: BTreeSet::new(),
381 terms: BTreeMap::new(),
382 roots: BTreeMap::new(),
383 fields: network
384 .links()
385 .filter(|link| {
386 link.metadata().link_type() == Some(LinkType::Field)
387 && link.references().len() == 3
388 })
389 .map(|link| link.references()[0])
390 .collect(),
391 }
392 }
393
394 fn node(
395 &mut self,
396 id: LinkId,
397 kind: &str,
398 arity: Option<usize>,
399 ) -> Result<(Vec<LinkId>, Option<String>), String> {
400 let link = self
401 .network
402 .link(id)
403 .ok_or_else(|| fail("a reference is dangling"))?;
404 self.visited.insert(id);
405 if self.visited.len() > self.node_limit {
406 return Err(fail("the structural node limit is exceeded"));
407 }
408 let data = link.metadata();
409 if data.link_type() != Some(LinkType::Semantic)
410 || !data.is_named()
411 || data.language() != schema()["language"].as_str()
412 || data.term() != schema()["terms"][kind].as_str()
413 {
414 return Err(fail("a semantic node has a foreign role or model"));
415 }
416 if data.span().is_some() || data.flags() != LinkFlags::clean() {
417 return Err(fail(
418 "a semantic node carries unsupported concrete metadata",
419 ));
420 }
421 if self.fields.contains(&id) {
422 return Err(fail(
423 "positional semantic nodes cannot conceal named fields",
424 ));
425 }
426 if arity.is_some_and(|arity| link.references().len() != arity) {
427 return Err(fail("a semantic node has the wrong arity"));
428 }
429 if !["text", "position", "model", "root"].contains(&kind) && data.definition().is_some() {
430 return Err(fail("a semantic node has unexpected scalar data"));
431 }
432 Ok((
433 link.references().to_vec(),
434 data.definition().map(str::to_owned),
435 ))
436 }
437
438 fn text(&mut self, id: LinkId) -> Result<String, String> {
439 let (_, definition) = self.node(id, "text", Some(0))?;
440 let value = Value::String(definition.ok_or_else(|| fail("a linked text value is absent"))?);
441 Ok(bounded_text(&value)?.to_owned())
442 }
443
444 fn sequence(&mut self, id: LinkId) -> Result<Vec<LinkId>, String> {
445 Ok(self.node(id, "sequence", None)?.0)
446 }
447
448 fn model(&mut self, id: LinkId) -> Result<(), String> {
449 let (references, definition) = self.node(id, "model", Some(1))?;
450 if definition.as_deref() != schema()["model"].as_str()
451 || self.text(references[0])? != schema()["specification"]
452 {
453 return Err(fail(
454 "the selected term equality premises are not supported",
455 ));
456 }
457 Ok(())
458 }
459
460 fn term(&mut self, id: LinkId) -> Result<Value, String> {
461 if let Some(term) = self.terms.get(&id) {
462 return Ok(term.clone());
463 }
464 if !self.active.insert(id) {
465 return Err(fail("a term has a structural cycle"));
466 }
467 let label = self
468 .network
469 .link(id)
470 .and_then(|link| link.metadata().term());
471 let kind = ["identifier", "blank", "literal"]
472 .into_iter()
473 .find(|kind| label == schema()["terms"][kind].as_str())
474 .ok_or_else(|| fail("a statement reference is not a resource term"))?;
475 let fields = self
476 .node(
477 id,
478 kind,
479 Some(match kind {
480 "identifier" => 1,
481 "blank" => 2,
482 _ => 3,
483 }),
484 )?
485 .0;
486 let input = match kind {
487 "identifier" => json!({"kind":kind,"value":self.text(fields[0])?}),
488 "blank" => {
489 json!({"kind":kind,"sourceIdentifier":self.text(fields[0])?,"value":self.text(fields[1])?})
490 }
491 _ => {
492 self.node(fields[1], "identifier", Some(1))?;
493 let datatype = self.term(fields[1])?;
494 json!({"kind":kind,"value":self.text(fields[0])?,"datatype":datatype["value"],"language":self.text(fields[2])?})
495 }
496 };
497 let normalized = normalized_term(&input, None)?;
498 if kind == "literal" && normalized["language"] != input["language"] {
499 return Err(fail("a semantic language tag must be canonical lowercase"));
500 }
501 self.terms.insert(id, normalized.clone());
502 self.active.remove(&id);
503 Ok(normalized)
504 }
505
506 fn statement(&mut self, id: LinkId) -> Result<Vec<Value>, String> {
507 let triple = self
508 .node(id, "statement", Some(3))?
509 .0
510 .into_iter()
511 .map(|id| self.term(id))
512 .collect::<Result<Vec<_>, _>>()?;
513 check_positions(&triple)?;
514 Ok(triple)
515 }
516
517 fn graph(&mut self, root: LinkId, depth: usize) -> Result<Graph, String> {
518 if depth > 64 {
519 return Err(fail("the source graph nesting limit is exceeded"));
520 }
521 if let Some(graph) = self.roots.get(&root) {
522 return Ok(graph.clone());
523 }
524 if !self.active.insert(root) {
525 return Err(fail("source graph provenance is cyclic"));
526 }
527 let (fields, revision) = self.node(root, "root", Some(5))?;
528 if revision.as_deref() != Some("1") {
529 return Err(fail("the graph schema revision is unsupported"));
530 }
531 self.model(fields[0])?;
532 let statement_ids = self.sequence(fields[1])?;
533 let mut signatures = BTreeSet::new();
534 let mut triples = Vec::new();
535 for id in &statement_ids {
536 let triple = self.statement(*id)?;
537 if !signatures.insert(statement_identity(&triple)) {
538 return Err(fail("the graph statement set contains a duplicate"));
539 }
540 triples.push(triple);
541 }
542 let mut occurrences = Vec::new();
543 for id in self.sequence(fields[2])? {
544 let references = self.node(id, "occurrence", Some(4))?.0;
545 let index = statement_ids
546 .iter()
547 .position(|id| *id == references[0])
548 .ok_or_else(|| fail("an occurrence refers outside its graph statement set"))?;
549 let source = self.text(references[1])?;
550 let (_, position_text) = self.node(references[2], "position", Some(0))?;
551 let position_text =
552 position_text.ok_or_else(|| fail("an occurrence source position is invalid"))?;
553 let position = position_text
554 .parse::<u64>()
555 .map_err(|_| fail("an occurrence source position is invalid"))?;
556 if position > 9_007_199_254_740_991 || position.to_string() != position_text {
557 return Err(fail("an occurrence source position is invalid"));
558 }
559 let language = self.text(references[3])?;
560 let semantic_language = if triples[index][2]["kind"] == "literal" {
561 triples[index][2]["language"].as_str().unwrap()
562 } else {
563 ""
564 };
565 if source.is_empty() || language.to_lowercase() != semantic_language {
566 return Err(fail(
567 "an occurrence source or language provenance is inconsistent",
568 ));
569 }
570 occurrences.push(json!({"statementIndex":index,"sourceIdentifier":source,"position":position,"sourceLanguage":language}));
571 }
572 let sources = self.sequence(fields[3])?;
573 for id in &sources {
574 self.graph(*id, depth + 1)?;
575 }
576 let mut owned = BTreeSet::new();
577 let mut pending = sources;
578 while let Some(id) = pending.pop() {
579 if owned.contains(&id) {
580 continue;
581 }
582 if owned.len() >= self.node_limit {
583 return Err(fail("the provenance traversal limit is exceeded"));
584 }
585 owned.insert(id);
586 let link = self
587 .network
588 .link(id)
589 .ok_or_else(|| fail("a source provenance reference is dangling"))?;
590 pending.extend_from_slice(link.references());
591 }
592 let target_terms = statement_ids
593 .iter()
594 .flat_map(|id| self.network.link(*id).unwrap().references().iter().copied())
595 .collect::<BTreeSet<_>>();
596 for id in self.sequence(fields[4])? {
597 let references = self.node(id, "witness", Some(3))?.0;
598 self.model(references[2])?;
599 if !owned.contains(&references[0])
600 || !target_terms.contains(&references[1])
601 || !same(&self.term(references[0])?, &self.term(references[1])?)
602 {
603 return Err(fail(
604 "a term equality witness has false or unowned premises",
605 ));
606 }
607 }
608 self.active.remove(&root);
609 let result = Graph {
610 triples,
611 occurrences,
612 statement_ids,
613 };
614 self.roots.insert(root, result.clone());
615 Ok(result)
616 }
617}
618
619pub fn decode_resource_description_graph(
624 network: &LinkNetwork,
625 root: LinkId,
626) -> Result<Value, String> {
627 decode_resource_description_graph_with_limit(network, root, 100_000)
628}
629
630pub fn decode_resource_description_graph_with_limit(
635 network: &LinkNetwork,
636 root: LinkId,
637 node_limit: usize,
638) -> Result<Value, String> {
639 if node_limit == 0
640 || !u64::try_from(node_limit).is_ok_and(|limit| limit <= 9_007_199_254_740_991)
641 {
642 return Err(fail("a positive structural limit is required"));
643 }
644 let graph = Reader::new(network, node_limit).graph(root, 0)?;
645 Ok(json!({"model":schema()["model"],"triples":graph.triples,"occurrences":graph.occurrences}))
646}
647
648pub fn merge_resource_description_graphs(
653 inputs: &[ResourceDescriptionLinks],
654) -> Result<ResourceDescriptionLinks, String> {
655 if inputs.len() > 100 {
656 return Err(fail("a bounded source graph list is required"));
657 }
658 let mut output = Writer::new()?;
659 for input in inputs {
660 let mut reader = Reader::new(&input.network, 100_000);
661 let graph = reader.graph(input.root, 0)?;
662 let mut copied = BTreeMap::new();
663 let mut pending = vec![input.root];
664 while let Some(id) = pending.pop() {
665 if copied.contains_key(&id) {
666 continue;
667 }
668 if copied.len() >= 100_000 {
669 return Err(fail("the source copy limit is exceeded"));
670 }
671 let link = input
672 .network
673 .link(id)
674 .ok_or_else(|| fail("a source reference is dangling"))?;
675 copied.insert(id, output.append(&[], link.metadata().clone())?);
676 pending.extend_from_slice(link.references());
677 }
678 for (before, after) in &copied {
679 let references = input
680 .network
681 .link(*before)
682 .unwrap()
683 .references()
684 .iter()
685 .map(|id| copied[id])
686 .collect::<Vec<_>>();
687 output.network.set_references(*after, &references);
688 }
689 output.sources.push(copied[&input.root]);
690 for occurrence in &graph.occurrences {
691 let index = usize::try_from(occurrence["statementIndex"].as_u64().unwrap()).unwrap();
692 output.occurrence(
693 &graph.triples[index],
694 occurrence["sourceIdentifier"].as_str().unwrap(),
695 occurrence["position"].as_u64().unwrap(),
696 occurrence["sourceLanguage"].as_str().unwrap(),
697 )?;
698 }
699 for triple in &graph.triples {
700 output.statement(triple)?;
701 }
702 let source_terms = graph
703 .statement_ids
704 .iter()
705 .flat_map(|id| {
706 input
707 .network
708 .link(*id)
709 .unwrap()
710 .references()
711 .iter()
712 .copied()
713 })
714 .collect::<BTreeSet<_>>();
715 for before in source_terms {
716 let target = output.term(&reader.term(before)?)?;
717 let witness = output.node("witness", &[copied[&before], target, output.model], None)?;
718 output.witnesses.push(witness);
719 }
720 }
721 let result = output.finish()?;
722 decode_resource_description_graph(&result.network, result.root)?;
723 Ok(result)
724}
725
726pub fn verify_resource_description_graph_witnesses(
731 network: &LinkNetwork,
732 root: LinkId,
733) -> Result<bool, String> {
734 decode_resource_description_graph(network, root)?;
735 Ok(true)
736}