1use std::collections::HashMap;
7use std::io;
8
9use crate::q42_lex::{LexError, Q42LexMmap};
10use crate::q42_volume::Q42Volume;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum CborLdError {
15 InvalidCbor,
16 InvalidValueType,
17 MissingField,
18 UnsupportedFeature,
19 InvalidOffset,
20 InvalidUtf8,
21}
22
23#[derive(Debug, Clone)]
25pub struct SemanticPayload {
26 pub data: Vec<u8>,
27 pub context: Q42Context,
28 pub semantic_context: HashMap<String, String>,
29 pub did_q42: Option<String>,
30 pub wireguard_pubkey: Option<String>,
31 pub routing_constraints: Vec<String>,
32 pub peer_capabilities: HashMap<String, String>,
33}
34
35#[derive(Debug, Clone)]
37pub struct Q42Context {
38 pub base_iri: String,
39 pub vocabulary: HashMap<String, String>,
40}
41
42impl Q42Context {
43 pub fn new() -> Self {
45 let mut vocabulary = HashMap::new();
46 vocabulary.insert(
47 "rdf".to_string(),
48 "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
49 );
50 vocabulary.insert(
55 "rdfs".to_string(),
56 "http://www.w3.org/2000/01/rdf-schema#".to_string(),
57 );
58 vocabulary.insert("sh".to_string(), "http://www.w3.org/ns/shacl#".to_string());
59 vocabulary.insert(
60 "owl".to_string(),
61 "http://www.w3.org/2002/07/owl#".to_string(),
62 );
63 vocabulary.insert(
64 "xsd".to_string(),
65 "http://www.w3.org/2001/XMLSchema#".to_string(),
66 );
67 vocabulary.insert("hcai".to_string(), "http://www.w3.org/ns/hcai#".to_string());
68 vocabulary.insert(
69 "qualia".to_string(),
70 "https://webizen.org/ld/vocab/".to_string(),
71 );
72
73 Self {
74 base_iri: "https://webizen.org/ld/context/v1".to_string(),
75 vocabulary,
76 }
77 }
78
79 pub fn from_volume(volume: &Q42Volume) -> Result<Self, io::Error> {
81 let mut context = Self::new();
82 let lex_view = volume.lex_view().map_err(|e| {
83 io::Error::new(
84 io::ErrorKind::InvalidData,
85 format!("Invalid volume lexicon: {:?}", e),
86 )
87 })?;
88
89 for i in 0..lex_view.entry_count() {
91 let Some(hash) = lex_view.hash_at(i) else {
92 break;
93 };
94 if let Some(text) = lex_view
95 .lookup_webizen_identity(hash).map(str::to_owned)
96 .or_else(|| lex_view.lookup_owned(hash))
97 {
98 if let Some(colon_pos) = text.find(':') {
99 let prefix = &text[..colon_pos];
100 let uri = &text[colon_pos + 1..];
101 if uri.starts_with("http://")
102 || uri.starts_with("https://")
103 || uri.starts_with("urn:")
104 {
105 context
106 .vocabulary
107 .insert(prefix.to_string(), uri.to_string());
108 }
109 }
110 }
111 }
112
113 if let Ok(Some(manifest_bytes)) = volume.volume_manifest_bytes() {
115 if let Ok(manifest_str) = std::str::from_utf8(manifest_bytes) {
116 for line in manifest_str.lines() {
117 let line = line.trim();
118 if let Some(base) = line.strip_prefix("@base ") {
119 context.base_iri = base
120 .trim_matches(|c| c == '<' || c == '>' || c == '"' || c == ';')
121 .to_string();
122 } else if let Some(prefix_decl) = line.strip_prefix("@prefix ") {
123 let parts: Vec<&str> = prefix_decl.split_whitespace().collect();
124 if parts.len() >= 2 {
125 let prefix = parts[0].trim_end_matches(':');
126 let uri = parts[1].trim_matches(|c| c == '<' || c == '>' || c == ';');
127 context
128 .vocabulary
129 .insert(prefix.to_string(), uri.to_string());
130 }
131 }
132 }
133 }
134 }
135
136 Ok(context)
137 }
138
139 pub fn resolve_semantic_term(&self, term: &str) -> Option<String> {
141 self.vocabulary.get(term).cloned()
142 }
143
144 pub fn context_hash(&self) -> u64 {
147 let mut entries: Vec<(&String, &String)> = self.vocabulary.iter().collect();
148 entries.sort_by_key(|(k, _)| *k);
149 let mut combined = self.base_iri.clone();
150 for (k, v) in entries {
151 combined.push_str(k);
152 combined.push_str(v);
153 }
154 crate::q_hash(&combined)
155 }
156
157 pub fn expand_to_hash(&self, compact_iri: &str) -> u64 {
160 let expanded = if let Some(colon) = compact_iri.find(':') {
161 let (prefix, suffix) = (&compact_iri[..colon], &compact_iri[colon + 1..]);
162 match self.vocabulary.get(prefix) {
163 Some(base) => format!("{base}{suffix}"),
164 None => compact_iri.to_string(),
165 }
166 } else {
167 compact_iri.to_string()
168 };
169 crate::q_hash(&expanded)
170 }
171}
172
173impl Default for Q42Context {
174 fn default() -> Self {
175 Self::new()
176 }
177}
178
179#[derive(Debug, Clone)]
181pub struct Q42CborLdParser {
182 lexicon: Q42Lexicon,
183}
184
185impl Q42CborLdParser {
186 pub fn new(lexicon: Q42Lexicon) -> Self {
188 Self { lexicon }
189 }
190
191 pub fn from_volume(volume: &Q42Volume) -> Result<Self, io::Error> {
193 let lexicon = Q42Lexicon::from_volume(volume).map_err(|_| {
194 io::Error::new(
195 io::ErrorKind::InvalidData,
196 "Failed to load lexicon from volume",
197 )
198 })?;
199 Ok(Self::new(lexicon))
200 }
201
202 pub fn lexicon(&self) -> &Q42Lexicon {
205 &self.lexicon
206 }
207
208 pub fn parse(&self, data: &[u8]) -> Result<SemanticPayload, CborLdError> {
210 Ok(SemanticPayload {
211 data: data.to_vec(),
212 context: Q42Context::new(),
213 semantic_context: HashMap::new(),
214 did_q42: None,
215 wireguard_pubkey: None,
216 routing_constraints: Vec::new(),
217 peer_capabilities: HashMap::new(),
218 })
219 }
220
221 pub fn parse_semantic_payload(&self, data: &[u8]) -> Result<SemanticPayload, CborLdError> {
223 self.parse(data)
224 }
225}
226
227#[derive(Debug, Clone)]
229pub struct Q42Lexicon {
230 pub terms: HashMap<String, u64>,
232 pub reverse: HashMap<u64, String>,
234 pub version: LexiconVersion,
237 pub context_uri: String,
239 pub vocabulary: HashMap<String, String>,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub enum LexiconVersion {
245 V2,
246}
247
248impl LexiconVersion {
249 pub fn v2() -> Self {
251 LexiconVersion::V2
252 }
253}
254
255impl Q42Lexicon {
256 pub fn new() -> Self {
258 let mut vocabulary = HashMap::new();
259 vocabulary.insert(
260 "rdf".to_string(),
261 "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
262 );
263 vocabulary.insert(
267 "rdfs".to_string(),
268 "http://www.w3.org/2000/01/rdf-schema#".to_string(),
269 );
270 vocabulary.insert("sh".to_string(), "http://www.w3.org/ns/shacl#".to_string());
271 vocabulary.insert(
272 "owl".to_string(),
273 "http://www.w3.org/2002/07/owl#".to_string(),
274 );
275 vocabulary.insert(
276 "xsd".to_string(),
277 "http://www.w3.org/2001/XMLSchema#".to_string(),
278 );
279 vocabulary.insert("hcai".to_string(), "http://www.w3.org/ns/hcai#".to_string());
280 vocabulary.insert(
281 "qualia".to_string(),
282 "https://webizen.org/ld/vocab/".to_string(),
283 );
284 vocabulary.insert(
285 "did".to_string(),
286 "https://www.w3.org/TR/did-core/".to_string(),
287 );
288 vocabulary.insert("sec".to_string(), "https://w3id.org/security/".to_string());
289
290 Self {
291 terms: HashMap::new(),
292 reverse: HashMap::new(),
293 version: LexiconVersion::v2(),
294 context_uri: "https://webizen.org/ld/context/v1".to_string(),
295 vocabulary,
296 }
297 }
298
299 pub fn from_volume(volume: &Q42Volume) -> Result<Self, LexError> {
301 let lex_data = volume.lex_bytes();
302 let lex_view = Q42LexMmap::from_bytes(lex_data)?;
303
304 let mut terms = HashMap::new();
305 let mut reverse = HashMap::new();
306
307 for i in 0..lex_view.entry_count() {
310 let Some(hash) = lex_view.hash_at(i) else {
311 break;
312 };
313 if let Some(text) = lex_view
314 .lookup_webizen_identity(hash).map(str::to_owned)
315 .or_else(|| lex_view.lookup_owned(hash))
316 {
317 terms.insert(text.clone(), hash);
318 reverse.insert(hash, text);
319 }
320 }
321
322 let vocabulary = Self::new().vocabulary;
323
324 Ok(Self {
325 terms,
326 reverse,
327 version: LexiconVersion::v2(),
328 context_uri: "https://webizen.org/ld/context/v1".to_string(),
329 vocabulary,
330 })
331 }
332
333 pub fn resolve_term(&self, term: &str) -> Option<u64> {
335 self.terms.get(term).copied()
336 }
337
338 pub fn resolve_hash(&self, hash: u64) -> Option<&str> {
340 self.reverse.get(&hash).map(|s| s.as_str())
341 }
342
343 pub fn contains_term(&self, term: &str) -> bool {
345 self.terms.contains_key(term)
346 }
347
348 pub fn contains_hash(&self, hash: u64) -> bool {
350 self.reverse.contains_key(&hash)
351 }
352
353 pub fn add_term(&mut self, term: String, hash: u64) {
355 self.terms.insert(term.clone(), hash);
356 self.reverse.insert(hash, term);
357 }
358
359 pub fn expand_iri(&self, compact_iri: &str) -> Option<String> {
361 if let Some(colon_pos) = compact_iri.find(':') {
362 let prefix = &compact_iri[..colon_pos];
363 let suffix = &compact_iri[colon_pos + 1..];
364 self.vocabulary
365 .get(prefix)
366 .map(|base| format!("{}{}", base, suffix))
367 } else {
368 None
369 }
370 }
371
372 pub fn vocabulary(&self) -> &HashMap<String, String> {
374 &self.vocabulary
375 }
376}
377
378impl Default for Q42Lexicon {
379 fn default() -> Self {
380 Self::new()
381 }
382}
383
384#[cfg(test)]
385#[path = "q42_lexicon_tests.rs"]
386mod tests;