Skip to main content

clm_rust_core/layer2/
collection.rs

1//! Carrier Collection interface for MCard operations across runtimes (Sprint 552 / INV-552).
2//!
3//! Exposes handle, raw-byte, and manifest operations aligned with TypeScript
4//! `MCardCollection` and Python `CardCollection`.
5
6use crate::error::Result;
7use crate::layer0::mcard_record::MCardRecord;
8use crate::layer2::vfs::{DirectoryManifest, MCardFileSystem};
9use rusqlite::Connection;
10use std::sync::{Arc, Mutex};
11
12/// Carrier collection interface for MCard operations across runtimes (INV-552).
13#[derive(Clone)]
14pub struct MCardCollection {
15    fs: MCardFileSystem,
16}
17
18impl MCardCollection {
19    /// Create a collection wrapping an existing MCardFileSystem.
20    pub fn new(fs: MCardFileSystem) -> Self {
21        Self { fs }
22    }
23
24    /// Initializes an isolated, in-memory MCardCollection.
25    pub fn new_in_memory() -> Result<Self> {
26        let fs = MCardFileSystem::new_in_memory()?;
27        Ok(Self { fs })
28    }
29
30    /// Wraps an existing shared SQLite connection.
31    pub fn from_connection(conn: Arc<Mutex<Connection>>) -> Self {
32        let fs = MCardFileSystem::new(conn, "");
33        Self { fs }
34    }
35
36    /// Access the underlying MCardFileSystem.
37    pub fn fs(&self) -> &MCardFileSystem {
38        &self.fs
39    }
40
41    /// Writes raw content bytes into `card` and binds `uri` in `handle_registry` (`INV-510-01`, `INV-510-02`).
42    pub fn write_raw_bytes(
43        &self,
44        uri: &str,
45        content: &[u8],
46        algorithm: Option<&str>,
47    ) -> Result<MCardRecord> {
48        self.fs.write_raw_bytes(uri, content, algorithm)
49    }
50
51    /// Reads and verifies exact raw bytes bound to `uri` (`INV-510-01`).
52    pub fn read_raw_bytes(&self, uri: &str) -> Result<Vec<u8>> {
53        self.fs.read_raw_bytes(uri)
54    }
55
56    /// Atomic Compare-and-Swap handle binding (`INV-510-03`).
57    pub fn bind(&self, uri: &str, new_ref: &str, expected_old_ref: Option<&str>) -> Result<bool> {
58        self.fs.bind(uri, new_ref, expected_old_ref)
59    }
60
61    /// Writes a `DirectoryManifest` `MCard` to `dir_uri` (`INV-510-04`).
62    pub fn write_directory_manifest(
63        &self,
64        dir_uri: &str,
65        manifest: &DirectoryManifest,
66    ) -> Result<MCardRecord> {
67        self.fs.write_directory_manifest(dir_uri, manifest)
68    }
69
70    /// Reads a `DirectoryManifest` `MCard` from `dir_uri` (`INV-510-04`).
71    pub fn read_directory_manifest(&self, dir_uri: &str) -> Result<DirectoryManifest> {
72        self.fs.read_directory_manifest(dir_uri)
73    }
74}