Skip to main content

oxilite_jsonld/
options.rs

1//! How documents are keyed and where their RDF goes.
2//!
3// @lat: [[architecture#JSON-LD documents#Keys and graphs]]
4
5use crate::error::{JsonLdError, Result};
6use json_syntax::Value;
7use oxrdf::{GraphName, NamedNode};
8use sha2::{Digest, Sha256};
9use std::collections::BTreeMap;
10use std::fmt::Write;
11use std::sync::Arc;
12
13/// Prefix of content-hash keys: `urn:oxilite:doc:sha256:<hex>`.
14pub const CONTENT_HASH_PREFIX: &str = "urn:oxilite:doc:sha256:";
15
16/// Where a document's key comes from.
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
18pub enum KeyStrategy {
19    /// The top-level `@id` or `id` (the default; a credential's id).
20    #[default]
21    Id,
22    /// A JSON Pointer (RFC 6901) to a string, e.g. `/credentialSubject/id`.
23    Pointer(String),
24    /// `urn:oxilite:doc:sha256:<hex>` of the document bytes.
25    ContentHash,
26    /// The caller passes the key with every write.
27    Explicit,
28}
29
30/// What happens when the key strategy finds no key.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum MissingKey {
33    /// Fail with [`JsonLdError::MissingKey`] (the generic default).
34    #[default]
35    Reject,
36    /// Use the content-hash key (the credentials default).
37    ContentHash,
38}
39
40/// Which graph a document's default-graph triples go to.
41#[derive(Debug, Clone, PartialEq, Eq, Default)]
42pub enum GraphStrategy {
43    /// The key itself, as a named graph IRI (the default).
44    #[default]
45    Key,
46    /// An IRI template; `{key}` is replaced by the percent-encoded key.
47    Template(String),
48    /// One named graph shared by all documents.
49    Fixed(NamedNode),
50    /// The default graph.
51    DefaultGraph,
52}
53
54impl GraphStrategy {
55    /// Does each document get a graph of its own? (Then replace and remove clear it whole.)
56    pub fn owns_target(&self) -> bool {
57        matches!(self, Self::Key | Self::Template(_))
58    }
59}
60
61/// How `@direction` is represented in RDF (JSON-LD `rdfDirection`).
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum RdfDirection {
64    /// `https://www.w3.org/ns/i18n#{lang}_{dir}` datatypes.
65    I18nDatatype,
66    /// `rdf:CompoundLiteral` nodes.
67    CompoundLiteral,
68}
69
70/// JSON-LD processing mode.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum ProcessingMode {
73    /// JSON-LD 1.0 (rejects 1.1 features).
74    JsonLd10,
75    /// JSON-LD 1.1 (the default).
76    #[default]
77    JsonLd11,
78}
79
80/// Fetches a remote context's JSON by IRI (network access, native only; see `http_fetcher`).
81pub type ContextFetcher = Arc<dyn Fn(&str) -> Result<String> + Send + Sync>;
82
83/// Which document metadata columns are indexed (the columns are always filled).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct MetadataIndexes {
86    pub issuer: bool,
87    pub subject: bool,
88    pub valid_until: bool,
89}
90
91impl Default for MetadataIndexes {
92    fn default() -> Self {
93        Self {
94            issuer: true,
95            subject: true,
96            valid_until: true,
97        }
98    }
99}
100
101impl MetadataIndexes {
102    /// No metadata index (cheapest writes on D1).
103    pub fn none() -> Self {
104        Self {
105            issuer: false,
106            subject: false,
107            valid_until: false,
108        }
109    }
110}
111
112/// Options of a JSON-LD document handle.
113#[derive(Clone, Default)]
114pub struct JsonLdOptions {
115    pub key: KeyStrategy,
116    pub on_missing_key: MissingKey,
117    pub graph: GraphStrategy,
118    /// Base IRI for relative IRIs in documents.
119    pub base_iri: Option<String>,
120    pub rdf_direction: Option<RdfDirection>,
121    pub processing_mode: ProcessingMode,
122    /// Contexts available without loading: IRI → JSON text.
123    pub contexts: BTreeMap<String, String>,
124    /// Fetches unknown contexts (off by default: no network access).
125    pub fetcher: Option<ContextFetcher>,
126    /// Persist fetched contexts in `jsonld_contexts`, so later loads need no network.
127    pub cache_fetched: bool,
128    /// Metadata indexes created with the schema.
129    pub indexes: MetadataIndexes,
130}
131
132impl std::fmt::Debug for JsonLdOptions {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("JsonLdOptions")
135            .field("key", &self.key)
136            .field("on_missing_key", &self.on_missing_key)
137            .field("graph", &self.graph)
138            .field("base_iri", &self.base_iri)
139            .field("rdf_direction", &self.rdf_direction)
140            .field("processing_mode", &self.processing_mode)
141            .field("contexts", &self.contexts.keys().collect::<Vec<_>>())
142            .field("fetcher", &self.fetcher.is_some())
143            .field("cache_fetched", &self.cache_fetched)
144            .field("indexes", &self.indexes)
145            .finish()
146    }
147}
148
149impl JsonLdOptions {
150    /// Registers a context in memory (IRI → JSON text).
151    pub fn with_context(mut self, iri: impl Into<String>, json: impl Into<String>) -> Self {
152        self.contexts.insert(iri.into(), json.into());
153        self
154    }
155
156    /// Resolves a document's key.
157    pub fn key_for(&self, raw: &str, doc: &Value, explicit: Option<&str>) -> Result<String> {
158        if let Some(k) = explicit {
159            return Ok(k.to_owned());
160        }
161        let found = match &self.key {
162            KeyStrategy::Id => top_level_id(doc),
163            KeyStrategy::Pointer(p) => pointer(doc, p).and_then(|v| v.as_str().map(str::to_owned)),
164            KeyStrategy::ContentHash => return Ok(content_hash_key(raw)),
165            KeyStrategy::Explicit => None,
166        };
167        match found {
168            Some(k) if !k.is_empty() => Ok(k),
169            _ => match self.on_missing_key {
170                MissingKey::ContentHash => Ok(content_hash_key(raw)),
171                MissingKey::Reject => Err(JsonLdError::MissingKey(match &self.key {
172                    KeyStrategy::Id => "no top-level @id or id".into(),
173                    KeyStrategy::Pointer(p) => format!("no string at {p}"),
174                    _ => "no key was passed".into(),
175                })),
176            },
177        }
178    }
179
180    /// The graph a document with this key writes to.
181    pub fn graph_for(&self, key: &str) -> Result<GraphName> {
182        Ok(match &self.graph {
183            GraphStrategy::Key => GraphName::NamedNode(parse_iri(key)?),
184            GraphStrategy::Template(t) => {
185                GraphName::NamedNode(parse_iri(&t.replace("{key}", &percent_encode(key)))?)
186            }
187            GraphStrategy::Fixed(g) => GraphName::NamedNode(g.clone()),
188            GraphStrategy::DefaultGraph => GraphName::DefaultGraph,
189        })
190    }
191}
192
193fn parse_iri(s: &str) -> Result<NamedNode> {
194    NamedNode::new(s).map_err(|e| JsonLdError::InvalidGraphName(format!("{s}: {e}")))
195}
196
197/// The top-level `@id`/`id` of a document (a string).
198pub fn top_level_id(doc: &Value) -> Option<String> {
199    let o = doc.as_object()?;
200    for k in ["@id", "id"] {
201        if let Some(v) = o.get_unique(k).ok().flatten() {
202            return v.as_str().map(str::to_owned);
203        }
204    }
205    None
206}
207
208/// Resolves a JSON Pointer (RFC 6901).
209pub fn pointer<'a>(doc: &'a Value, pointer: &str) -> Option<&'a Value> {
210    if pointer.is_empty() {
211        return Some(doc);
212    }
213    let mut cur = doc;
214    for token in pointer.strip_prefix('/')?.split('/') {
215        let token = token.replace("~1", "/").replace("~0", "~");
216        cur = match cur {
217            Value::Object(o) => o.get_unique(token.as_str()).ok().flatten()?,
218            Value::Array(a) => a.get(token.parse::<usize>().ok()?)?,
219            _ => return None,
220        };
221    }
222    Some(cur)
223}
224
225/// SHA-256 of the document bytes.
226pub fn sha256(raw: &str) -> [u8; 32] {
227    Sha256::digest(raw.as_bytes()).into()
228}
229
230/// Lower-case hex.
231pub fn hex(bytes: &[u8]) -> String {
232    let mut s = String::with_capacity(bytes.len() * 2);
233    for b in bytes {
234        let _ = write!(s, "{b:02x}");
235    }
236    s
237}
238
239/// `urn:oxilite:doc:sha256:<hex>` of the document bytes.
240pub fn content_hash_key(raw: &str) -> String {
241    format!("{CONTENT_HASH_PREFIX}{}", hex(&sha256(raw)))
242}
243
244/// Percent-encodes everything but RFC 3986 `pchar`s and `/`.
245pub fn percent_encode(s: &str) -> String {
246    let mut out = String::with_capacity(s.len());
247    for b in s.bytes() {
248        if b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/".contains(&b) {
249            out.push(b as char);
250        } else {
251            let _ = write!(out, "%{b:02X}");
252        }
253    }
254    out
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use json_syntax::Parse;
261
262    fn parse(s: &str) -> Value {
263        Value::parse_str(s).unwrap().0
264    }
265
266    #[test]
267    fn keys() {
268        let raw =
269            r#"{"id": "https://example.org/docs/1", "credentialSubject": {"id": "did:ex:1"}}"#;
270        let doc = parse(raw);
271        let o = JsonLdOptions::default();
272        assert_eq!(
273            o.key_for(raw, &doc, None).unwrap(),
274            "https://example.org/docs/1"
275        );
276        let o = JsonLdOptions {
277            key: KeyStrategy::Pointer("/credentialSubject/id".into()),
278            ..Default::default()
279        };
280        assert_eq!(o.key_for(raw, &doc, None).unwrap(), "did:ex:1");
281        let o = JsonLdOptions {
282            key: KeyStrategy::Pointer("/nope".into()),
283            ..Default::default()
284        };
285        assert!(matches!(
286            o.key_for(raw, &doc, None),
287            Err(JsonLdError::MissingKey(_))
288        ));
289    }
290
291    #[test]
292    fn templates() {
293        let o = JsonLdOptions {
294            graph: GraphStrategy::Template("https://example.org/g/{key}".into()),
295            ..Default::default()
296        };
297        assert_eq!(
298            o.graph_for("a b").unwrap(),
299            GraphName::NamedNode(NamedNode::new_unchecked("https://example.org/g/a%20b"))
300        );
301        assert!(matches!(
302            JsonLdOptions::default().graph_for("not an iri"),
303            Err(JsonLdError::InvalidGraphName(_))
304        ));
305    }
306}