Skip to main content

binoc_sdk/
data_access.rs

1use std::path::{Path, PathBuf};
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::sync::Mutex;
4
5use crate::types::{ArtifactDescriptor, ArtifactFormat, ArtifactSubject};
6use crate::{BinocError, BinocResult, DataAccess, ItemRef};
7
8/// In-process DataAccess backed by the local filesystem, temp directories,
9/// and a filesystem-backed artifact store under `data_root/.artifacts/`.
10///
11/// Construction modes:
12///
13/// - [`Self::new`] — unrestricted paths (tests, ad-hoc tooling).
14/// - [`Self::new_for_diff`] — paths must stay under the two snapshot trees or
15///   session workspace (used by the controller).
16/// - [`Self::for_plugin`] — shares the host's `data_root` for artifact access,
17///   plus a pre-allocated workspace for expansion (C ABI plugins).
18/// - [`Self::with_data_root`] — shares an existing `data_root` for artifact
19///   reads only (no expansion workspace).
20pub struct LocalDataAccess {
21    #[cfg(not(target_family = "wasm"))]
22    _session_dir: Option<tempfile::TempDir>,
23    #[cfg(target_family = "wasm")]
24    _session_dir: Option<PathBuf>,
25    data_root: PathBuf,
26    external_root: Option<PathBuf>,
27    workspace_counter: AtomicU32,
28    #[cfg(not(target_family = "wasm"))]
29    workspaces: Mutex<Vec<tempfile::TempDir>>,
30    #[cfg(target_family = "wasm")]
31    workspaces: Mutex<Vec<PathBuf>>,
32    #[cfg(not(target_family = "wasm"))]
33    provide_dir: Mutex<Option<tempfile::TempDir>>,
34    #[cfg(target_family = "wasm")]
35    provide_dir: Mutex<Option<PathBuf>>,
36    path_policy: PathPolicy,
37}
38
39enum PathPolicy {
40    Unrestricted,
41    Restricted {
42        snapshot_a: PathBuf,
43        snapshot_b: PathBuf,
44        extra_allowed: Mutex<Vec<PathBuf>>,
45    },
46}
47
48fn artifacts_dir(data_root: &Path) -> PathBuf {
49    data_root.join(".artifacts")
50}
51
52fn safe_name(s: &str) -> String {
53    s.bytes()
54        .map(|b| {
55            if b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' {
56                (b as char).to_string()
57            } else {
58                format!("%{b:02x}")
59            }
60        })
61        .collect()
62}
63
64fn subject_dir_name(subject: ArtifactSubject) -> &'static str {
65    match subject {
66        ArtifactSubject::Left => "left",
67        ArtifactSubject::Right => "right",
68        ArtifactSubject::Pair => "pair",
69    }
70}
71
72#[cfg(target_family = "wasm")]
73fn policy_path(path: &Path) -> BinocResult<PathBuf> {
74    let mut out = PathBuf::new();
75    for component in path.components() {
76        match component {
77            std::path::Component::Prefix(_) => {}
78            std::path::Component::RootDir => {}
79            std::path::Component::CurDir => {}
80            std::path::Component::ParentDir => {
81                out.pop();
82            }
83            std::path::Component::Normal(part) => out.push(part),
84        }
85    }
86    Ok(out)
87}
88
89#[cfg(not(target_family = "wasm"))]
90fn policy_path(path: &Path) -> BinocResult<PathBuf> {
91    std::fs::canonicalize(path).map_err(BinocError::Io)
92}
93
94#[cfg(target_family = "wasm")]
95fn wasm_session_dir(prefix: &str) -> PathBuf {
96    let id: u64 = rand::random();
97    PathBuf::from(".binoc-tmp").join(format!("{prefix}-{id:016x}"))
98}
99
100#[cfg(target_family = "wasm")]
101fn temp_path(dir: &Path) -> &Path {
102    dir
103}
104
105#[cfg(not(target_family = "wasm"))]
106fn temp_path(dir: &tempfile::TempDir) -> &Path {
107    dir.path()
108}
109
110/// True when `path` is `root` or a descendant (component-wise).
111fn path_is_within(path: &Path, root: &Path) -> bool {
112    path.starts_with(root)
113}
114
115fn item_ref_from_physical(physical: &Path, logical: &str) -> ItemRef {
116    ItemRef {
117        logical_path: logical.to_string(),
118        is_dir: physical.is_dir(),
119        content_hash: None,
120        size: None,
121        media_type: None,
122        projection_hint: Default::default(),
123        handle: physical.to_string_lossy().to_string(),
124    }
125}
126
127impl LocalDataAccess {
128    #[cfg(not(target_family = "wasm"))]
129    pub fn new() -> Self {
130        let session = tempfile::tempdir().expect("failed to create session temp dir");
131        let data_root = session.path().to_path_buf();
132        Self {
133            _session_dir: Some(session),
134            data_root,
135            external_root: None,
136            workspace_counter: AtomicU32::new(0),
137            workspaces: Mutex::new(Vec::new()),
138            provide_dir: Mutex::new(None),
139            path_policy: PathPolicy::Unrestricted,
140        }
141    }
142
143    #[cfg(target_family = "wasm")]
144    pub fn new() -> Self {
145        let data_root = wasm_session_dir("session");
146        std::fs::create_dir_all(&data_root).expect("failed to create session temp dir");
147        Self {
148            _session_dir: Some(data_root.clone()),
149            data_root,
150            external_root: None,
151            workspace_counter: AtomicU32::new(0),
152            workspaces: Mutex::new(Vec::new()),
153            provide_dir: Mutex::new(None),
154            path_policy: PathPolicy::Unrestricted,
155        }
156    }
157
158    /// Session-backed access with path confinement: filesystem reads and
159    /// `register_local` targets must lie under the snapshot roots, the session
160    /// `data_root`, or a workspace / provide directory created by this instance.
161    #[cfg(not(target_family = "wasm"))]
162    pub fn new_for_diff(snapshot_a: &Path, snapshot_b: &Path) -> BinocResult<Self> {
163        let session = tempfile::tempdir().map_err(BinocError::Io)?;
164        let data_root = session.path().to_path_buf();
165        let snap_a = std::fs::canonicalize(snapshot_a).map_err(BinocError::Io)?;
166        let snap_b = std::fs::canonicalize(snapshot_b).map_err(BinocError::Io)?;
167        let data_root_canon = std::fs::canonicalize(&data_root).map_err(BinocError::Io)?;
168        Ok(Self {
169            _session_dir: Some(session),
170            data_root,
171            external_root: None,
172            workspace_counter: AtomicU32::new(0),
173            workspaces: Mutex::new(Vec::new()),
174            provide_dir: Mutex::new(None),
175            path_policy: PathPolicy::Restricted {
176                snapshot_a: snap_a,
177                snapshot_b: snap_b,
178                extra_allowed: Mutex::new(vec![data_root_canon]),
179            },
180        })
181    }
182
183    #[cfg(target_family = "wasm")]
184    pub fn new_for_diff(snapshot_a: &Path, snapshot_b: &Path) -> BinocResult<Self> {
185        let data_root = wasm_session_dir("session");
186        std::fs::create_dir_all(&data_root).map_err(BinocError::Io)?;
187        let snap_a = policy_path(snapshot_a)?;
188        let snap_b = policy_path(snapshot_b)?;
189        let data_root_canon = policy_path(&data_root)?;
190        Ok(Self {
191            _session_dir: Some(data_root),
192            data_root: data_root_canon.clone(),
193            external_root: None,
194            workspace_counter: AtomicU32::new(0),
195            workspaces: Mutex::new(Vec::new()),
196            provide_dir: Mutex::new(None),
197            path_policy: PathPolicy::Restricted {
198                snapshot_a: snap_a,
199                snapshot_b: snap_b,
200                extra_allowed: Mutex::new(vec![data_root_canon]),
201            },
202        })
203    }
204
205    /// Create a LocalDataAccess for a plugin running across the C ABI.
206    /// Shares the host's `data_root` for cache access and uses `workspace`
207    /// for expansion (provide, workspace calls).
208    pub fn for_plugin(data_root: PathBuf, workspace: PathBuf) -> Self {
209        Self {
210            _session_dir: None,
211            data_root,
212            external_root: Some(workspace),
213            workspace_counter: AtomicU32::new(0),
214            workspaces: Mutex::new(Vec::new()),
215            provide_dir: Mutex::new(None),
216            path_policy: PathPolicy::Unrestricted,
217        }
218    }
219
220    /// Create a LocalDataAccess that can only read from an existing data_root
221    /// cache. No workspace for expansion. Used during extract-only access.
222    pub fn with_data_root(data_root: PathBuf) -> Self {
223        Self {
224            _session_dir: None,
225            data_root,
226            external_root: None,
227            workspace_counter: AtomicU32::new(0),
228            workspaces: Mutex::new(Vec::new()),
229            provide_dir: Mutex::new(None),
230            path_policy: PathPolicy::Unrestricted,
231        }
232    }
233
234    fn record_allowed_if_restricted(&self, path: &Path) -> BinocResult<()> {
235        if let PathPolicy::Restricted { extra_allowed, .. } = &self.path_policy {
236            let c = policy_path(path)?;
237            extra_allowed.lock().unwrap().push(c);
238        }
239        Ok(())
240    }
241
242    fn enforce_path_policy_resolved(&self, resolved: &Path) -> BinocResult<()> {
243        match &self.path_policy {
244            PathPolicy::Unrestricted => Ok(()),
245            PathPolicy::Restricted {
246                snapshot_a,
247                snapshot_b,
248                extra_allowed,
249            } => {
250                if path_is_within(resolved, snapshot_a) || path_is_within(resolved, snapshot_b) {
251                    return Ok(());
252                }
253                let roots = extra_allowed.lock().unwrap();
254                for root in roots.iter() {
255                    if path_is_within(resolved, root) {
256                        return Ok(());
257                    }
258                }
259                Err(BinocError::PathPolicy(format!(
260                    "path must stay under snapshot directories or session workspace: {}",
261                    resolved.display()
262                )))
263            }
264        }
265    }
266
267    /// Enforce policy for a path that must already exist on disk (e.g. `register_local`).
268    fn enforce_path_policy(&self, physical: &Path) -> BinocResult<()> {
269        let resolved = policy_path(physical)?;
270        self.enforce_path_policy_resolved(&resolved)
271    }
272
273    /// Enforce policy before reading; allows missing leaf paths under an allowed directory.
274    #[cfg(not(target_family = "wasm"))]
275    fn enforce_policy_for_read_path(&self, path: &Path) -> BinocResult<()> {
276        match &self.path_policy {
277            PathPolicy::Unrestricted => Ok(()),
278            PathPolicy::Restricted { .. } => {
279                if let Ok(c) = std::fs::canonicalize(path) {
280                    return self.enforce_path_policy_resolved(&c);
281                }
282                let mut probe: Option<&Path> = Some(path);
283                while let Some(p) = probe {
284                    if p.as_os_str().is_empty() {
285                        break;
286                    }
287                    if p.exists() {
288                        let base = std::fs::canonicalize(p).map_err(BinocError::Io)?;
289                        self.enforce_path_policy_resolved(&base)?;
290                        return Ok(());
291                    }
292                    probe = p.parent();
293                }
294                Err(BinocError::PathPolicy(format!(
295                    "cannot resolve path under session: {}",
296                    path.display()
297                )))
298            }
299        }
300    }
301
302    #[cfg(target_family = "wasm")]
303    fn enforce_policy_for_read_path(&self, path: &Path) -> BinocResult<()> {
304        match &self.path_policy {
305            PathPolicy::Unrestricted => Ok(()),
306            PathPolicy::Restricted { .. } => self.enforce_path_policy_resolved(&policy_path(path)?),
307        }
308    }
309
310    fn ensure_provide_dir(&self) -> BinocResult<PathBuf> {
311        if let Some(root) = &self.external_root {
312            let d = root.join("_provide");
313            std::fs::create_dir_all(&d).map_err(BinocError::Io)?;
314            self.record_allowed_if_restricted(&d)?;
315            return Ok(d);
316        }
317        let mut guard = self.provide_dir.lock().unwrap();
318        if guard.is_none() {
319            #[cfg(not(target_family = "wasm"))]
320            let dir = tempfile::tempdir().map_err(BinocError::Io)?;
321            #[cfg(target_family = "wasm")]
322            let dir = {
323                let dir = wasm_session_dir("provide");
324                std::fs::create_dir_all(&dir).map_err(BinocError::Io)?;
325                dir
326            };
327            self.record_allowed_if_restricted(temp_path(&dir))?;
328            *guard = Some(dir);
329        }
330        Ok(temp_path(guard.as_ref().unwrap()).to_path_buf())
331    }
332}
333
334impl Default for LocalDataAccess {
335    fn default() -> Self {
336        Self::new()
337    }
338}
339
340impl DataAccess for LocalDataAccess {
341    fn read_bytes(&self, item: &ItemRef) -> BinocResult<Vec<u8>> {
342        let p = Path::new(&item.handle);
343        self.enforce_policy_for_read_path(p)?;
344        std::fs::read(p).map_err(BinocError::Io)
345    }
346
347    fn open_read(&self, item: &ItemRef) -> BinocResult<Box<dyn std::io::Read + Send>> {
348        let p = Path::new(&item.handle);
349        self.enforce_policy_for_read_path(p)?;
350        let file = std::fs::File::open(p).map_err(BinocError::Io)?;
351        Ok(Box::new(file))
352    }
353
354    fn local_path(&self, item: &ItemRef) -> BinocResult<PathBuf> {
355        let p = PathBuf::from(&item.handle);
356        self.enforce_policy_for_read_path(&p)?;
357        Ok(p)
358    }
359
360    fn provide(&self, logical_path: &str, content: &[u8]) -> BinocResult<ItemRef> {
361        let dir = self.ensure_provide_dir()?;
362        let safe_name = logical_path.replace(['/', '\\'], "_");
363        let file_path = dir.join(&safe_name);
364        std::fs::write(&file_path, content).map_err(BinocError::Io)?;
365        self.enforce_path_policy(&file_path)?;
366        Ok(item_ref_from_physical(&file_path, logical_path))
367    }
368
369    fn workspace(&self) -> BinocResult<PathBuf> {
370        if let Some(root) = &self.external_root {
371            let n = self.workspace_counter.fetch_add(1, Ordering::Relaxed);
372            let subdir = root.join(format!("ws-{n}"));
373            std::fs::create_dir_all(&subdir).map_err(BinocError::Io)?;
374            self.record_allowed_if_restricted(&subdir)?;
375            return Ok(subdir);
376        }
377        #[cfg(not(target_family = "wasm"))]
378        let dir = tempfile::tempdir().map_err(BinocError::Io)?;
379        #[cfg(target_family = "wasm")]
380        let dir = {
381            let dir = wasm_session_dir("workspace");
382            std::fs::create_dir_all(&dir).map_err(BinocError::Io)?;
383            dir
384        };
385        let path = temp_path(&dir).to_path_buf();
386        self.record_allowed_if_restricted(&path)?;
387        self.workspaces.lock().unwrap().push(dir);
388        Ok(path)
389    }
390
391    fn register_local(&self, physical: &Path, logical: &str) -> BinocResult<ItemRef> {
392        self.enforce_path_policy(physical)?;
393        Ok(item_ref_from_physical(physical, logical))
394    }
395
396    fn publish_artifact(
397        &self,
398        format: &ArtifactFormat,
399        subject: ArtifactSubject,
400        producer: &str,
401        data: &[u8],
402    ) -> BinocResult<ArtifactDescriptor> {
403        let id: u64 = rand::random();
404        let dir = artifacts_dir(&self.data_root)
405            .join(safe_name(&format.package))
406            .join(safe_name(&format.name))
407            .join(format!("v{}", format.version))
408            .join(subject_dir_name(subject));
409        std::fs::create_dir_all(&dir).map_err(BinocError::Io)?;
410        let filename = format!("{}-{id:016x}", safe_name(producer));
411        let handle = dir.join(filename).to_string_lossy().to_string();
412        std::fs::write(&handle, data).map_err(BinocError::Io)?;
413        Ok(ArtifactDescriptor {
414            format: format.clone(),
415            subject,
416            producer: producer.to_string(),
417            handle,
418        })
419    }
420
421    fn get_artifact(&self, descriptor: &ArtifactDescriptor) -> BinocResult<Option<Vec<u8>>> {
422        let path = PathBuf::from(&descriptor.handle);
423        self.enforce_policy_for_read_path(&path)?;
424        match std::fs::read(&path) {
425            Ok(data) => Ok(Some(data)),
426            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
427            Err(e) => Err(BinocError::Io(e)),
428        }
429    }
430
431    fn data_root(&self) -> BinocResult<PathBuf> {
432        Ok(self.data_root.clone())
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    #[test]
441    fn publish_and_get_artifact_round_trip() {
442        let da = LocalDataAccess::new();
443        let fmt = ArtifactFormat::new("binoc", "tabular", 1);
444        let desc = da
445            .publish_artifact(&fmt, ArtifactSubject::Left, "binoc.csv", b"hello world")
446            .unwrap();
447        assert_eq!(desc.format, fmt);
448        assert_eq!(desc.subject, ArtifactSubject::Left);
449        assert_eq!(desc.producer, "binoc.csv");
450        let loaded = da.get_artifact(&desc).unwrap();
451        assert_eq!(loaded, Some(b"hello world".to_vec()));
452    }
453
454    #[test]
455    fn get_artifact_missing_returns_none() {
456        let da = LocalDataAccess::new();
457        let desc = ArtifactDescriptor {
458            format: ArtifactFormat::new("nonexistent", "thing", 1),
459            subject: ArtifactSubject::Pair,
460            producer: "test".into(),
461            handle: "/tmp/does-not-exist-binoc-test".into(),
462        };
463        assert_eq!(da.get_artifact(&desc).unwrap(), None);
464    }
465
466    #[test]
467    fn cross_instance_artifact_visibility() {
468        let da = LocalDataAccess::new();
469        let fmt = ArtifactFormat::new("binoc", "tabular", 1);
470        let desc = da
471            .publish_artifact(&fmt, ArtifactSubject::Right, "binoc.csv", b"shared-value")
472            .unwrap();
473        let data_root = da.data_root().unwrap();
474
475        let plugin_da = LocalDataAccess::with_data_root(data_root);
476        let loaded = plugin_da.get_artifact(&desc).unwrap();
477        assert_eq!(loaded, Some(b"shared-value".to_vec()));
478    }
479
480    #[test]
481    fn for_plugin_shares_artifacts() {
482        let da = LocalDataAccess::new();
483        let data_root = da.data_root().unwrap();
484        let ws = da.workspace().unwrap();
485
486        let plugin_da = LocalDataAccess::for_plugin(data_root, ws);
487        let fmt = ArtifactFormat::new("myplugin", "schema", 1);
488        let desc = plugin_da
489            .publish_artifact(&fmt, ArtifactSubject::Pair, "myplugin", b"plugin-data")
490            .unwrap();
491
492        let loaded = da.get_artifact(&desc).unwrap();
493        assert_eq!(loaded, Some(b"plugin-data".to_vec()));
494    }
495
496    #[test]
497    fn data_root_returns_valid_path() {
498        let da = LocalDataAccess::new();
499        let root = da.data_root().unwrap();
500        assert!(root.exists());
501    }
502
503    #[test]
504    fn restricted_rejects_register_outside_snapshots() {
505        let tmp_a = tempfile::tempdir().unwrap();
506        let tmp_b = tempfile::tempdir().unwrap();
507        let outside = tempfile::tempdir().unwrap();
508        std::fs::write(outside.path().join("x.txt"), b"x").unwrap();
509
510        let da = LocalDataAccess::new_for_diff(tmp_a.path(), tmp_b.path()).unwrap();
511        let p = outside.path().join("x.txt");
512        let err = da.register_local(&p, "x.txt").unwrap_err();
513        assert!(matches!(err, BinocError::PathPolicy(_)));
514    }
515
516    #[test]
517    fn restricted_allows_register_under_snapshot() {
518        let tmp_a = tempfile::tempdir().unwrap();
519        let tmp_b = tempfile::tempdir().unwrap();
520        let f = tmp_a.path().join("f.txt");
521        std::fs::write(&f, b"ok").unwrap();
522
523        let da = LocalDataAccess::new_for_diff(tmp_a.path(), tmp_b.path()).unwrap();
524        da.register_local(&f, "f.txt").unwrap();
525    }
526}