Skip to main content

link_cli/protocol/
server_query.rs

1//! Checked request execution shared by the generic and session servers.
2use super::*;
3
4/// Executes one request against `storage`.
5///
6/// A non-empty document is a substitution query; the reply holds one
7/// `(before) (after)` line per change, exactly like `clink --changes`. The
8/// empty document asks for every link, one `(index: source target)` per line.
9/// Failures produce an [`error_document`].
10pub fn execute_request<S: NamedTypeLinks>(
11    storage: &mut S,
12    processor: &QueryProcessor,
13    document: &[LiNo<String>],
14) -> LinoDocument {
15    execute_observed_request(storage, processor, document, &mut Vec::new())
16}
17
18/// Executes a u32 request and records its net changes for subscriptions.
19pub(crate) fn execute_observed_request<S: NamedTypeLinks>(
20    storage: &mut S,
21    processor: &QueryProcessor,
22    document: &[LiNo<String>],
23    changed: &mut Vec<Change>,
24) -> LinoDocument {
25    match try_execute_request(storage, processor, document, changed) {
26        Ok(reply) => reply,
27        Err(error) => error_document(&format!("{error:#}")),
28    }
29}
30
31/// Executes an owned protocol document with the selected address type.
32/// Checked storage policies admit the document before recursive formatting.
33pub fn execute_request_for<T: QueryAddress, S: NamedTypeLinks<T>>(
34    storage: &mut S,
35    processor: &GenericQueryProcessor<T>,
36    document: &[LiNo<String>],
37) -> LinoDocument {
38    match try_execute_request(storage, processor, document, &mut Vec::new()) {
39        Ok(reply) => reply,
40        Err(error) => error_document(&format!("{error:#}")),
41    }
42}
43
44fn try_execute_request<T: QueryAddress, S: NamedTypeLinks<T>>(
45    storage: &mut S,
46    processor: &GenericQueryProcessor<T>,
47    document: &[LiNo<String>],
48    changed: &mut Vec<Change<T>>,
49) -> anyhow::Result<LinoDocument> {
50    if let Some(limits) = storage.query_limits() {
51        admit_document(document, limits)?;
52    }
53    // A canonical document does not retain quoted-reference kinds. The envelope
54    // carries original query text as one value through both text and binary.
55    let original = match document {
56        [LiNo::Link {
57            id: Some(id),
58            values,
59        }] if id == "query" => {
60            let [LiNo::Ref(text)] = values.as_slice() else {
61                anyhow::bail!("expected (query: original-query-text)");
62            };
63            Some(text.as_str())
64        }
65        _ => None,
66    };
67    if original.is_none() {
68        if let Some(operation) = GenericLinksOperation::<T>::from_document(document)? {
69            let reply = operation.execute(storage)?;
70            if matches!(
71                operation,
72                GenericLinksOperation::Create { .. }
73                    | GenericLinksOperation::Update { .. }
74                    | GenericLinksOperation::Delete(_)
75            ) {
76                changed.extend(parse_changes_for::<T>(&reply)?);
77            }
78            return Ok(reply);
79        }
80    }
81    if document.is_empty() || original.is_some_and(|text| text.trim().is_empty()) {
82        let mut budget = QueryReplyBudget::new(storage.query_limits());
83        let mut links = storage.all_links();
84        if let Some(limits) = storage.query_limits() {
85            anyhow::ensure!(
86                links.len() <= limits.max_results,
87                "protocol result limit exceeded"
88            );
89        }
90        links.sort_by_key(|link| link.index);
91        return links
92            .iter()
93            .map(|link| link_lino(storage, link, &mut budget))
94            .collect();
95    }
96    let legacy_text;
97    let text = match original {
98        Some(text) => text,
99        None => {
100            legacy_text = format_document(document);
101            &legacy_text
102        }
103    };
104    let changes = processor.process_query(storage, text)?;
105    changed.extend(changes.iter().map(|(before, after)| {
106        (
107            before.unwrap_or_else(GenericLink::null),
108            after.unwrap_or_else(GenericLink::null),
109        )
110    }));
111    if !changes.is_empty() {
112        storage.save()?;
113    }
114    let mut budget = QueryReplyBudget::new(storage.query_limits());
115    changes
116        .iter()
117        .map(|(before, after)| {
118            Ok(LiNo::Link {
119                id: None,
120                values: vec![
121                    change_side(storage, before.as_ref(), &mut budget)?,
122                    change_side(storage, after.as_ref(), &mut budget)?,
123                ],
124            })
125        })
126        .collect()
127}
128
129/// `(index: source target)`, naming every reference that has a name.
130fn link_lino<T: QueryAddress, S: NamedTypeLinks<T> + ?Sized>(
131    storage: &mut S,
132    link: &GenericLink<T>,
133    budget: &mut QueryReplyBudget,
134) -> anyhow::Result<LiNo<String>> {
135    Ok(LiNo::Link {
136        id: Some(budget.reference(storage, link.index)?),
137        values: vec![
138            LiNo::Ref(budget.reference(storage, link.source)?),
139            LiNo::Ref(budget.reference(storage, link.target)?),
140        ],
141    })
142}
143
144/// `()` for a missing side of a change, `((index: source target))` otherwise.
145fn change_side<T: QueryAddress, S: NamedTypeLinks<T> + ?Sized>(
146    storage: &mut S,
147    link: Option<&GenericLink<T>>,
148    budget: &mut QueryReplyBudget,
149) -> anyhow::Result<LiNo<String>> {
150    let values = match link {
151        Some(link) => vec![link_lino(storage, link, budget)?],
152        None => Vec::new(),
153    };
154    Ok(LiNo::Link { id: None, values })
155}
156
157/// Carries the exact original query text, including quoted-reference kinds.
158/// Older peers must explicitly support this envelope before a client uses it.
159pub fn query_document(text: &str) -> LinoDocument {
160    vec![LiNo::Link {
161        id: Some("query".into()),
162        values: vec![LiNo::Ref(text.into())],
163    }]
164}
165
166pub(crate) fn admit_document(document: &[LiNo<String>], limits: QueryLimits) -> anyhow::Result<()> {
167    anyhow::ensure!(
168        document.len() <= limits.max_nodes,
169        "protocol node limit exceeded"
170    );
171    let mut pending: Vec<_> = document.iter().map(|node| (node, 0usize)).collect();
172    let mut admitted = document.len();
173    let mut bytes = 0usize;
174    while let Some((node, depth)) = pending.pop() {
175        anyhow::ensure!(depth <= limits.max_depth, "protocol depth limit exceeded");
176        match node {
177            LiNo::Ref(value) => bytes = bytes.saturating_add(value.len()),
178            LiNo::Link { id, values } => {
179                bytes = bytes.saturating_add(id.as_ref().map_or(0, String::len));
180                admitted = admitted.saturating_add(values.len());
181                anyhow::ensure!(admitted <= limits.max_nodes, "protocol node limit exceeded");
182                pending.extend(values.iter().map(|node| (node, depth + 1)));
183            }
184        }
185        anyhow::ensure!(bytes <= limits.max_bytes, "protocol byte limit exceeded");
186    }
187    Ok(())
188}
189
190/// Parses bounded transport text before converting or formatting its document.
191/// The upstream grammar enforces depth before building its recursive model.
192pub fn parse_document_with_limits(text: &str, limits: QueryLimits) -> ProtocolResult<LinoDocument> {
193    use links_notation::{parse_lino_to_links_with_config, ParserConfig};
194    if text.len() > limits.max_bytes {
195        return Err(crate::protocol::error::ProtocolError::LimitExceeded(
196            "protocol byte limit exceeded".into(),
197        ));
198    }
199    if text.trim().is_empty() {
200        return Ok(Vec::new());
201    }
202    let document = parse_lino_to_links_with_config(
203        text,
204        &ParserConfig::new().with_max_depth(limits.max_depth),
205    )
206    .map_err(|error| crate::protocol::error::ProtocolError::InvalidLino(error.to_string()))?;
207    admit_document(&document, limits)
208        .map_err(|error| crate::protocol::error::ProtocolError::LimitExceeded(error.to_string()))?;
209    Ok(document
210        .into_iter()
211        .map(links_notation::binary::canonical)
212        .collect())
213}
214
215pub(crate) fn reference_name<S: NamedTypeLinks + ?Sized>(
216    storage: &mut S,
217    id: u32,
218) -> anyhow::Result<String> {
219    Ok(storage.get_name(id)?.unwrap_or_else(|| id.to_string()))
220}