Skip to main content

qualia_solid_bridge/
ldp_translator.rs

1//! LDP HTTP routes backed by [`crate::pod_store::PodStore`].
2//!
3//! Default builds still expose a small in-memory simulation when no store is
4//! attached (unit tests). Production/personal-pod serve attaches a real store.
5
6use crate::pod_store::PodStore;
7use qualia_core_db::modalities::logic::core::WebizenOpcode;
8use qualia_core_db::{q_hash, NQuin};
9use std::sync::Arc;
10use warp::http::{HeaderMap, HeaderValue, StatusCode};
11use warp::Filter;
12
13/// Simulated routes used by unit tests / no-store fallback.
14pub fn ldp_routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
15    let get_public =
16        warp::path!("public" / String)
17            .and(warp::get())
18            .map(|_resource_name: String| {
19                let turtle = "<urn:qualia:node:123> <urn:qualia:pred:456> <urn:qualia:node:789> .";
20                warp::reply::with_header(turtle, "content-type", "text/turtle")
21            });
22
23    let post_private = warp::path!("private" / String)
24        .and(warp::post())
25        .and(warp::body::bytes())
26        .map(|_folder: String, payload: bytes::Bytes| {
27            let compressed_quins = ldp_to_quins(&payload);
28            warp::reply::json(&serde_json::json!({
29                "status": "Stored via Bilateral Micro-Commons",
30                "quin_count": compressed_quins.len()
31            }))
32        });
33
34    get_public.or(post_private)
35}
36
37/// Full personal-pod LDP surface: GET/HEAD/PUT/POST/DELETE under the pod root.
38pub fn pod_ldp_routes(
39    store: Arc<PodStore>,
40    public_base: String,
41) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
42    let s_get = store.clone();
43    let base_get = public_base.clone();
44    let get = warp::path::full()
45        .and(warp::get())
46        .and(warp::header::optional::<String>("accept"))
47        .map(move |full: warp::path::FullPath, _accept: Option<String>| {
48            serve_get(&s_get, &base_get, full.as_str())
49        });
50
51    let s_put = store.clone();
52    let put = warp::path::full()
53        .and(warp::put())
54        .and(warp::body::bytes())
55        .map(move |full: warp::path::FullPath, body: bytes::Bytes| {
56            let path = full.as_str();
57            if path == "/" || path.is_empty() {
58                return reply_status(StatusCode::METHOD_NOT_ALLOWED, "cannot PUT pod root");
59            }
60            match s_put.write_bytes(path, &body) {
61                Ok(()) => {
62                    let mut headers = HeaderMap::new();
63                    headers.insert("content-type", HeaderValue::from_static("application/json"));
64                    headers.insert(
65                        "location",
66                        HeaderValue::from_str(path).unwrap_or(HeaderValue::from_static("/")),
67                    );
68                    json_reply(
69                        StatusCode::CREATED,
70                        headers,
71                        serde_json::json!({"ok": true, "path": path}),
72                    )
73                }
74                Err(e) => reply_status(StatusCode::BAD_REQUEST, &e.to_string()),
75            }
76        });
77
78    let s_post = store.clone();
79    let post = warp::path::full()
80        .and(warp::post())
81        .and(warp::body::bytes())
82        .and(warp::header::optional::<String>("slug"))
83        .map(
84            move |full: warp::path::FullPath, body: bytes::Bytes, slug: Option<String>| {
85                let path = full.as_str().trim_end_matches('/');
86                let name = slug.unwrap_or_else(|| {
87                    format!(
88                        "resource-{}.ttl",
89                        std::time::SystemTime::now()
90                            .duration_since(std::time::UNIX_EPOCH)
91                            .map(|d| d.as_millis())
92                            .unwrap_or(0)
93                    )
94                });
95                let target = if path.is_empty() || path == "/" {
96                    format!("/{}", name)
97                } else {
98                    format!("{}/{}", path, name)
99                };
100                // Also run allocation firewall on inbound
101                let _quins = ldp_to_quins(&body);
102                match s_post.write_bytes(&target, &body) {
103                    Ok(()) => {
104                        let mut headers = HeaderMap::new();
105                        headers.insert(
106                            "location",
107                            HeaderValue::from_str(&target).unwrap_or(HeaderValue::from_static("/")),
108                        );
109                        headers
110                            .insert("content-type", HeaderValue::from_static("application/json"));
111                        json_reply(
112                            StatusCode::CREATED,
113                            headers,
114                            serde_json::json!({
115                                "ok": true,
116                                "path": target,
117                                "note": "stored; inbound payload hashed to Quins at firewall"
118                            }),
119                        )
120                    }
121                    Err(e) => reply_status(StatusCode::BAD_REQUEST, &e.to_string()),
122                }
123            },
124        );
125
126    let s_del = store.clone();
127    let delete = warp::path::full()
128        .and(warp::delete())
129        .map(move |full: warp::path::FullPath| {
130            let path = full.as_str();
131            match s_del.delete(path) {
132                Ok(()) => reply_status(StatusCode::NO_CONTENT, ""),
133                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
134                    reply_status(StatusCode::NOT_FOUND, "not found")
135                }
136                Err(e) => reply_status(StatusCode::BAD_REQUEST, &e.to_string()),
137            }
138        });
139
140    // OPTIONS for CORS preflight is handled by warp::cors on the outer stack.
141    get.or(put).or(post).or(delete)
142}
143
144fn serve_get(store: &PodStore, public_base: &str, path: &str) -> warp::reply::Response {
145    let (status, headers, body) = serve_get_parts(store, public_base, path);
146    let mut resp = warp::http::Response::new(body.into());
147    *resp.status_mut() = status;
148    for (k, v) in headers.iter() {
149        resp.headers_mut().insert(k, v.clone());
150    }
151    resp
152}
153
154fn serve_get_parts(
155    store: &PodStore,
156    public_base: &str,
157    path: &str,
158) -> (StatusCode, HeaderMap, Vec<u8>) {
159    let mut headers = HeaderMap::new();
160    // Root → redirect attention to profile + containers
161    if path == "/" || path.is_empty() {
162        let index = format!(
163            r#"@prefix ldp: <http://www.w3.org/ns/ldp#> .
164@prefix solid: <http://www.w3.org/ns/solid/terms#> .
165
166<> a ldp:BasicContainer ;
167   ldp:contains <profile/>, <public/>, <private/>, <inbox/> .
168"#
169        );
170        headers.insert("content-type", HeaderValue::from_static("text/turtle"));
171        headers.insert(
172            "link",
173            HeaderValue::from_static(
174                r#"<http://www.w3.org/ns/ldp#BasicContainer>; rel="type", <http://www.w3.org/ns/ldp#Resource>; rel="type""#,
175            ),
176        );
177        let _ = public_base;
178        return (StatusCode::OK, headers, index.into_bytes());
179    }
180
181    match store.read_bytes(path) {
182        Ok(bytes) => {
183            let ct = if store.is_container(path) {
184                "text/turtle"
185            } else {
186                PodStore::content_type_for(path)
187            };
188            headers.insert(
189                "content-type",
190                HeaderValue::from_str(ct).unwrap_or(HeaderValue::from_static("text/turtle")),
191            );
192            // LDP types from bundled ldp.ttl (W3C ns archive)
193            let link = if store.is_container(path) {
194                format!(
195                    "<{}>; rel=\"type\", <{}>; rel=\"type\"",
196                    crate::vocab::LDP_BASIC_CONTAINER,
197                    crate::vocab::LDP_RESOURCE
198                )
199            } else {
200                format!("<{}>; rel=\"type\"", crate::vocab::LDP_RESOURCE)
201            };
202            if let Ok(v) = HeaderValue::from_str(&link) {
203                headers.insert("link", v);
204            }
205            // WAC discovery stub
206            let acl = format!("<{}/.acl>; rel=\"acl\"", path.trim_end_matches('/'));
207            if let Ok(v) = HeaderValue::from_str(&acl) {
208                headers.append("link", v);
209            }
210            (StatusCode::OK, headers, bytes)
211        }
212        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
213            headers.insert("content-type", HeaderValue::from_static("text/plain"));
214            (StatusCode::NOT_FOUND, headers, b"not found".to_vec())
215        }
216        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
217            headers.insert("content-type", HeaderValue::from_static("text/plain"));
218            (StatusCode::FORBIDDEN, headers, b"forbidden".to_vec())
219        }
220        Err(e) => {
221            headers.insert("content-type", HeaderValue::from_static("text/plain"));
222            (
223                StatusCode::INTERNAL_SERVER_ERROR,
224                headers,
225                e.to_string().into_bytes(),
226            )
227        }
228    }
229}
230
231fn reply_status(status: StatusCode, body: &str) -> warp::reply::Response {
232    let mut resp = warp::http::Response::new(body.to_string().into());
233    *resp.status_mut() = status;
234    resp.headers_mut().insert(
235        "content-type",
236        HeaderValue::from_static("text/plain; charset=utf-8"),
237    );
238    resp
239}
240
241fn json_reply(
242    status: StatusCode,
243    headers: HeaderMap,
244    value: serde_json::Value,
245) -> warp::reply::Response {
246    let body = serde_json::to_vec(&value).unwrap_or_default();
247    let mut resp = warp::http::Response::new(body.into());
248    *resp.status_mut() = status;
249    for (k, v) in headers.iter() {
250        resp.headers_mut().insert(k, v.clone());
251    }
252    if !resp.headers().contains_key("content-type") {
253        resp.headers_mut()
254            .insert("content-type", HeaderValue::from_static("application/json"));
255    }
256    resp
257}
258
259/// Translates a Solid payload into Super-Quins (allocation firewall).
260pub fn ldp_to_quins(payload: &[u8]) -> Vec<NQuin> {
261    // Prefer Turtle triple parse when payload looks like text RDF.
262    if let Ok(text) = std::str::from_utf8(payload) {
263        if text.contains('<') && text.contains('>') {
264            return crate::consumer::turtle_to_quins(text);
265        }
266    }
267    let mut quins = Vec::new();
268    let chunks = payload.chunks(128);
269    for chunk in chunks {
270        let subject = fast_hash_bytes(chunk);
271        let mut quin = NQuin {
272            subject,
273            predicate: q_hash("solid:contains"),
274            object: subject.wrapping_add(1),
275            context: q_hash("local:inbox"),
276            metadata: 0x4000_0000_0000_0000,
277            parity: 0,
278        };
279        quin.recalculate_parity();
280        quins.push(quin);
281    }
282    quins
283}
284
285fn fast_hash_bytes(bytes: &[u8]) -> u64 {
286    let mut hash: u64 = 0xcbf29ce484222325;
287    let mut i = 0;
288    while i < bytes.len() {
289        hash = hash ^ (bytes[i] as u64);
290        hash = hash.wrapping_mul(0x100000001b3);
291        i += 1;
292    }
293    hash & 0x0FFF_FFFF_FFFF_FFFF
294}
295
296/// Compiles a standard WAC .acl file down to Webizen Bytecode (N3Logic)
297pub fn compile_wac_to_bytecode(acl_body: &str) -> Vec<WebizenOpcode> {
298    let mut bytecode = Vec::new();
299    if acl_body.contains("acl:Read") {
300        bytecode.push(WebizenOpcode::EvalMetadataMask(0x01));
301    }
302    if acl_body.contains("acl:Write") {
303        bytecode.push(WebizenOpcode::MatchSubject(0));
304    }
305    bytecode.push(WebizenOpcode::HaltIfFalse);
306    bytecode
307}
308
309/// Translates a native Super-Quin vector back to JSON-LD (cold path).
310pub fn quins_to_ldp(quins: &[NQuin]) -> serde_json::Value {
311    let mut triples = Vec::new();
312    for q in quins {
313        triples.push(serde_json::json!({
314            "@id": format!("urn:hash:{}", q.subject),
315            "http://schema.org/predicate": q.predicate.to_string(),
316            "http://schema.org/object": q.object.to_string(),
317            "cml:context": q.context.to_string()
318        }));
319    }
320    serde_json::json!(triples)
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn test_allocation_firewall() {
329        #[cfg(feature = "dhat-heap")]
330        let _profiler = dhat::Profiler::new_heap();
331
332        let payload = vec![0x41; 5 * 1024 * 1024];
333
334        #[cfg(feature = "dhat-heap")]
335        let stats_before = dhat::HeapStats::get();
336
337        let quins = ldp_to_quins(&payload);
338
339        #[cfg(feature = "dhat-heap")]
340        let stats_after = dhat::HeapStats::get();
341
342        assert_eq!(quins.len(), 40960);
343        assert_eq!(quins[0].metadata, 0x4000_0000_0000_0000);
344
345        #[cfg(feature = "dhat-heap")]
346        {
347            let current_diff = stats_after.curr_bytes - stats_before.curr_bytes;
348            assert!(
349                current_diff < 3 * 1024 * 1024,
350                "Heap allocation firewall failed: {:?} bytes allocated",
351                current_diff
352            );
353        }
354    }
355
356    #[test]
357    fn test_acl_compilation() {
358        let acl = "
359        <#rule> a acl:Authorization;
360            acl:mode acl:Read, acl:Write .
361        ";
362        let bytecode = compile_wac_to_bytecode(acl);
363        assert!(bytecode.contains(&WebizenOpcode::MatchSubject(0)));
364        assert!(bytecode.contains(&WebizenOpcode::HaltIfFalse));
365    }
366
367    #[test]
368    fn turtle_inbound_uses_consumer_parser() {
369        let body = b"<urn:a> <urn:b> <urn:c> .\n";
370        let quins = ldp_to_quins(body);
371        assert_eq!(quins.len(), 1);
372        assert!(quins[0].verify_ecc_parity());
373    }
374}