1use std::collections::hash_map::RandomState;
7use std::collections::{HashMap, HashSet};
8use std::fmt::Write as _;
9use std::hash::{BuildHasher, Hasher};
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use links_notation::{LiNo, ParserConfig, parse_lino_to_links_with_config};
14use serde_json::Value;
15use sha2::{Digest, Sha256};
16
17use crate::structured_data_link_rules::{
18 accept_structured_data_record_field, accept_structured_data_record_shape,
19};
20use crate::structured_data_links::{
21 StructuredDataLinks, StructuredDataLinksLimits, StructuredDataValue,
22 encode_structured_data_links, encode_structured_data_links_ordered,
23 read_structured_data_lino_ordered_with_limits, read_structured_data_lino_with_limits,
24};
25use crate::{LinkId, LinkNetwork};
26
27fn fail(message: &str) -> String {
28 format!("structured data record: {message}")
29}
30
31fn accept_record_namespace(namespace: &str) -> bool {
32 let bytes = namespace.as_bytes();
33 bytes.len() == 36
34 && bytes.iter().enumerate().all(|(index, byte)| {
35 if matches!(index, 8 | 13 | 18 | 23) {
36 *byte == b'-'
37 } else {
38 byte.is_ascii_digit() || (b'a'..=b'f').contains(byte)
39 }
40 })
41 && (b'1'..=b'8').contains(&bytes[14])
42 && matches!(bytes[19], b'8' | b'9' | b'a' | b'b')
43}
44
45fn create_record_namespace() -> String {
46 static SEQUENCE: AtomicU64 = AtomicU64::new(0);
47 let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
48 let mut seed = RandomState::new().build_hasher();
49 seed.write_u64(sequence);
50 let mut digest = Sha256::new();
51 digest.update(seed.finish().to_le_bytes());
52 digest.update(std::process::id().to_le_bytes());
53 digest.update(sequence.to_le_bytes());
54 digest.update(
55 SystemTime::now()
56 .duration_since(UNIX_EPOCH)
57 .unwrap_or_default()
58 .as_nanos()
59 .to_le_bytes(),
60 );
61 let digest = digest.finalize();
62 let mut bytes = [0_u8; 16];
63 bytes.copy_from_slice(&digest[..16]);
64 bytes[6] = (bytes[6] & 0x0f) | 0x80;
67 bytes[8] = (bytes[8] & 0x3f) | 0x80;
68 let mut namespace = String::with_capacity(36);
69 for (index, byte) in bytes.iter().enumerate() {
70 if matches!(index, 4 | 6 | 8 | 10) {
71 namespace.push('-');
72 }
73 write!(namespace, "{byte:02x}").expect("writing a string succeeds");
74 }
75 namespace
76}
77
78fn encode_record_frame(graph: &StructuredDataLinks, namespace: &str) -> Result<String, String> {
79 if !accept_record_namespace(namespace) {
80 return Err(fail("invalid namespace"));
81 }
82 let mut output = format!("({namespace}/record: {namespace}/{}", graph.root);
83 let canonical = graph.network.to_lino();
86 for statement in canonical.lines() {
87 let (prefix, metadata) = statement
88 .split_once(" (meta:")
89 .ok_or_else(|| fail("canonical data statement lacks metadata"))?;
90 output.push_str(" (");
91 for (position, identity) in prefix[1..].split_ascii_whitespace().enumerate() {
92 if position > 0 {
93 output.push(' ');
94 }
95 write!(output, "{namespace}/{identity}").expect("writing a string succeeds");
96 }
97 output.push_str(" (meta:");
98 output.push_str(metadata);
99 }
100 output.push_str(" (meta: (t: semantic) (n: 1) (term: structured%20data%20record) (def: 1) (lang: meta-language%20structured%20data)))\n");
101 if output.len() > StructuredDataLinksLimits::default().byte_limit {
102 return Err(fail("serialized frame byte resource limit exceeded"));
103 }
104 Ok(output)
105}
106
107pub fn structured_data_record_to_lino(value: &Value) -> Result<String, String> {
109 structured_data_record_to_lino_with_namespace(value, &create_record_namespace())
110}
111
112pub fn structured_data_record_to_lino_with_namespace(
114 value: &Value,
115 namespace: &str,
116) -> Result<String, String> {
117 encode_record_frame(&encode_structured_data_links(value)?, namespace)
118}
119
120pub fn structured_data_record_to_lino_ordered(
122 value: &StructuredDataValue,
123) -> Result<String, String> {
124 structured_data_record_to_lino_ordered_with_namespace(value, &create_record_namespace())
125}
126
127pub fn structured_data_record_to_lino_ordered_with_namespace(
129 value: &StructuredDataValue,
130 namespace: &str,
131) -> Result<String, String> {
132 encode_record_frame(&encode_structured_data_links_ordered(value)?, namespace)
133}
134
135fn read_local_identity<'a>(identity: &'a str, namespace: &str) -> Result<&'a str, String> {
136 let local = identity
137 .strip_prefix(namespace)
138 .and_then(|identity| identity.strip_prefix('/'))
139 .ok_or_else(|| fail("foreign reference namespace"))?;
140 let number = local
141 .parse::<u64>()
142 .map_err(|_| fail("invalid local identity"))?;
143 if number == 0 || number > 9_007_199_254_740_991 || number.to_string() != local {
144 return Err(fail("invalid local identity"));
145 }
146 Ok(local)
147}
148
149fn write_record_metadata(node: &LiNo<String>, output: &mut String) -> Result<(), String> {
150 match node {
151 LiNo::Ref(value) => {
152 if value.is_empty()
154 || value.chars().any(|character| {
155 character.is_whitespace() || matches!(character, '(' | ')' | ':' | '"' | '\'')
156 })
157 {
158 return Err(fail("invalid data metadata token"));
159 }
160 output.push_str(value);
161 }
162 LiNo::Link {
163 id: Some(label),
164 values,
165 } => {
166 if !matches!(label.as_str(), "meta" | "t" | "n" | "term" | "def" | "lang") {
167 return Err(fail("invalid data metadata field"));
168 }
169 write!(output, "({label}:").expect("writing a string succeeds");
170 for value in values {
171 output.push(' ');
172 write_record_metadata(value, output)?;
173 }
174 output.push(')');
175 }
176 LiNo::Link { id: None, .. } => {
177 return Err(fail("invalid data metadata envelope"));
178 }
179 }
180 Ok(())
181}
182
183fn read_local_frame(
184 frame: &LiNo<String>,
185 namespaces: &mut HashSet<String>,
186 limits: StructuredDataLinksLimits,
187) -> Result<(String, LinkId), String> {
188 let LiNo::Link {
189 id: Some(identity),
190 values,
191 } = frame
192 else {
193 return Err(fail("invalid frame identity"));
194 };
195 let namespace = identity
196 .strip_suffix("/record")
197 .filter(|namespace| accept_record_namespace(namespace))
198 .ok_or_else(|| fail("invalid namespace"))?;
199 if !namespaces.insert(namespace.to_owned()) {
200 return Err(fail("duplicate namespace"));
201 }
202 let mut references = Vec::new();
203 let mut metadata = Vec::new();
204 let mut declarations = Vec::new();
205 for value in values {
206 match value {
207 LiNo::Ref(reference) => references.push(reference),
208 LiNo::Link {
209 id: Some(label),
210 values,
211 } if label == "meta" => metadata.push(values),
212 LiNo::Link { .. } => declarations.push(value),
213 }
214 }
215 if !accept_structured_data_record_shape(
216 &references.len().to_string(),
217 &metadata.len().to_string(),
218 ) {
219 return Err(fail("invalid frame shape"));
220 }
221 let root = read_local_identity(references[0], namespace)?;
222 let mut fields = HashSet::new();
223 for field in metadata[0] {
224 let LiNo::Link {
225 id: Some(label),
226 values,
227 } = field
228 else {
229 return Err(fail("invalid frame metadata"));
230 };
231 if values.len() != 1 || !fields.insert(label.as_str()) {
232 return Err(fail("invalid frame metadata"));
233 }
234 let LiNo::Ref(value) = &values[0] else {
235 return Err(fail("invalid frame metadata"));
236 };
237 if !accept_structured_data_record_field(label, value) {
238 return Err(fail("invalid frame metadata"));
239 }
240 }
241 if fields.len() != 5 {
242 return Err(fail("incomplete frame metadata"));
243 }
244 if declarations.len() > limits.node_limit {
245 return Err(fail("node resource limit exceeded"));
246 }
247 let mut identities = HashSet::new();
248 let mut declared_root = false;
249 let mut output = String::new();
250 for declaration in declarations {
251 let LiNo::Link {
252 id: Some(identity),
253 values,
254 } = declaration
255 else {
256 return Err(fail("invalid data declaration"));
257 };
258 let identity = read_local_identity(identity, namespace)?;
259 if !identities.insert(identity) {
260 return Err(fail("duplicate local identity"));
261 }
262 if identity == root {
263 declared_root = values.iter().any(|value| {
264 let LiNo::Link { id: Some(label), values } = value else {
265 return false;
266 };
267 label == "meta" && values.iter().any(|field| {
268 matches!(field, LiNo::Link { id: Some(label), values }
269 if label == "term" && matches!(values.as_slice(), [LiNo::Ref(term)] if term == "structured%20data"))
270 })
271 });
272 }
273 write!(output, "({identity}:").expect("writing a string succeeds");
274 for value in values {
275 output.push(' ');
276 if let LiNo::Ref(reference) = value {
277 output.push_str(read_local_identity(reference, namespace)?);
278 } else {
279 write_record_metadata(value, &mut output)?;
280 }
281 }
282 output.push_str(")\n");
283 }
284 if !declared_root {
287 return Err(fail("frame root is not a declared schema root"));
288 }
289 Ok((
290 output,
291 LinkId::from_u64(root.parse().map_err(|_| fail("invalid root identity"))?),
292 ))
293}
294
295fn read_record_graph_cost(
296 network: &LinkNetwork,
297 root: LinkId,
298 limits: StructuredDataLinksLimits,
299) -> Result<(usize, usize), String> {
300 fn visit(
301 network: &LinkNetwork,
302 id: LinkId,
303 depth: usize,
304 limits: StructuredDataLinksLimits,
305 costs: &mut HashMap<LinkId, (usize, usize)>,
306 ) -> Result<(usize, usize), String> {
307 if depth > limits.depth_limit {
308 return Err(fail("depth resource limit exceeded"));
309 }
310 if let Some(cost) = costs.get(&id) {
311 return Ok(*cost);
312 }
313 let link = network.link(id).ok_or_else(|| fail("dangling reference"))?;
314 let mut cost = (1_usize, link.metadata().definition().map_or(0, str::len));
315 for reference in link.references() {
316 let child = visit(network, *reference, depth + 1, limits, costs)?;
317 cost.0 = cost.0.saturating_add(child.0);
318 cost.1 = cost.1.saturating_add(child.1);
319 if cost.0 > limits.node_limit || cost.1 > limits.byte_limit {
320 return Err(fail("expanded data resource limit exceeded"));
321 }
322 }
323 costs.insert(id, cost);
324 Ok(cost)
325 }
326 visit(network, root, 0, limits, &mut HashMap::new())
328}
329
330fn read_record_frames<T>(
331 source: &str,
332 limits: StructuredDataLinksLimits,
333 decode: impl Fn(&str, StructuredDataLinksLimits) -> Result<T, String>,
334) -> Result<Vec<T>, String> {
335 if source.len() > limits.byte_limit {
336 return Err(fail("byte resource limit exceeded"));
337 }
338 let frames = parse_lino_to_links_with_config(
339 source,
340 &ParserConfig::without_comments().with_max_depth(10),
341 )
342 .map_err(|error| fail(&error.to_string()))?;
343 if frames.len() > limits.node_limit {
344 return Err(fail("record resource limit exceeded"));
345 }
346 let mut namespaces = HashSet::new();
347 let mut records = Vec::new();
348 let mut used = (0_usize, 0_usize);
349 for frame in &frames {
350 let (local, root) = read_local_frame(frame, &mut namespaces, limits)?;
351 let value = decode(&local, limits)?;
352 let network = LinkNetwork::from_lino(&local).map_err(|error| fail(&error.to_string()))?;
353 let cost = read_record_graph_cost(&network, root, limits)?;
354 used.0 = used.0.saturating_add(cost.0);
355 used.1 = used.1.saturating_add(cost.1);
356 if used.0 > limits.node_limit || used.1 > limits.byte_limit {
357 return Err(fail("aggregate record resource limit exceeded"));
358 }
359 records.push(value);
360 }
361 Ok(records)
362}
363
364pub fn read_structured_data_records(source: &str) -> Result<Vec<Value>, String> {
366 read_structured_data_records_with_limits(source, StructuredDataLinksLimits::default())
367}
368
369pub fn read_structured_data_records_with_limits(
371 source: &str,
372 limits: StructuredDataLinksLimits,
373) -> Result<Vec<Value>, String> {
374 read_record_frames(source, limits, read_structured_data_lino_with_limits)
375}
376
377pub fn read_structured_data_records_ordered(
379 source: &str,
380) -> Result<Vec<StructuredDataValue>, String> {
381 read_structured_data_records_ordered_with_limits(source, StructuredDataLinksLimits::default())
382}
383
384pub fn read_structured_data_records_ordered_with_limits(
386 source: &str,
387 limits: StructuredDataLinksLimits,
388) -> Result<Vec<StructuredDataValue>, String> {
389 read_record_frames(
390 source,
391 limits,
392 read_structured_data_lino_ordered_with_limits,
393 )
394}