Skip to main content

link_common/models/
file_ref.rs

1//! FILE column reference helpers for KalamDB SDKs.
2//!
3//! The core [`FileRef`] JSON model lives in `kalamdb-commons`. This module adds
4//! client-side context binding so SDK callers can generate URLs or download a
5//! file without passing namespace/table repeatedly.
6
7use std::ops::Deref;
8
9use kalamdb_commons::TableId;
10use serde::{Deserialize, Serialize};
11
12pub use kalamdb_commons::FileRef;
13
14/// Table context needed to locate a FILE column value for downloads.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(transparent)]
17pub struct FileRefContext(TableId);
18
19impl FileRefContext {
20    /// Create a new file reference context from a [`TableId`].
21    pub fn new(table_id: TableId) -> Self {
22        Self(table_id)
23    }
24
25    /// Create a file reference context from namespace and table name strings.
26    pub fn from_strings(namespace: &str, table: &str) -> Self {
27        Self(TableId::from_strings(namespace, table))
28    }
29
30    /// Borrow the table identity attached to this context.
31    pub fn table_id(&self) -> &TableId {
32        &self.0
33    }
34}
35
36/// A [`FileRef`] with table context attached.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct BoundFileRef {
39    file_ref: FileRef,
40    context: FileRefContext,
41}
42
43impl BoundFileRef {
44    /// Create a bound file reference from a raw file reference and context.
45    pub fn new(file_ref: FileRef, context: FileRefContext) -> Self {
46        Self { file_ref, context }
47    }
48
49    /// Borrow the underlying storage/wire file reference.
50    pub fn file_ref(&self) -> &FileRef {
51        &self.file_ref
52    }
53
54    /// Consume the bound reference and return the underlying file reference.
55    pub fn into_file_ref(self) -> FileRef {
56        self.file_ref
57    }
58
59    /// Borrow the context attached to this file reference.
60    pub fn context(&self) -> &FileRefContext {
61        &self.context
62    }
63
64    /// Table that owns the FILE column.
65    pub fn table_id(&self) -> &TableId {
66        self.context.table_id()
67    }
68
69    /// Namespace that owns the table.
70    pub fn namespace(&self) -> &str {
71        self.context.table_id().namespace_id().as_str()
72    }
73
74    /// Table that owns the FILE column.
75    pub fn table(&self) -> &str {
76        self.context.table_id().table_name().as_str()
77    }
78
79    /// Full download URL for this file.
80    pub fn download_url(&self, base_url: &str) -> String {
81        self.file_ref.download_url(base_url, self.namespace(), self.table())
82    }
83
84    /// Relative HTTP path for this file.
85    pub fn relative_url(&self) -> String {
86        self.file_ref.relative_url(self.namespace(), self.table())
87    }
88}
89
90impl Deref for BoundFileRef {
91    type Target = FileRef;
92
93    fn deref(&self) -> &Self::Target {
94        &self.file_ref
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn parse_from_json_string() {
104        let json = r#"{"id":"123","sub":"f0001","name":"test.png","size":1024,"mime":"image/png","sha256":"abc"}"#;
105        let fr = FileRef::from_json(json).unwrap();
106        assert_eq!(fr.id, "123");
107        assert_eq!(fr.sub, "f0001");
108        assert_eq!(fr.name, "test.png");
109        assert_eq!(fr.size, 1024);
110        assert!(fr.is_image());
111    }
112
113    #[test]
114    fn parse_from_json_value_object() {
115        let val = serde_json::json!({
116            "id": "456", "sub": "f0002", "name": "doc.pdf",
117            "size": 2048, "mime": "application/pdf", "sha256": "def"
118        });
119        let fr = FileRef::from_json_value(&val).unwrap();
120        assert!(fr.is_pdf());
121        assert_eq!(fr.type_description(), "PDF Document");
122    }
123
124    #[test]
125    fn parse_from_json_value_string() {
126        let inner = r#"{"id":"789","sub":"f0001","name":"a.txt","size":10,"mime":"text/plain","sha256":"x"}"#;
127        let val = serde_json::Value::String(inner.to_string());
128        let fr = FileRef::from_json_value(&val).unwrap();
129        assert_eq!(fr.id, "789");
130    }
131
132    #[test]
133    fn download_url_generation() {
134        let fr = FileRef {
135            id: "123".into(),
136            sub: "f0001".into(),
137            name: "t.png".into(),
138            size: 0,
139            mime: "image/png".into(),
140            sha256: String::new(),
141            shard: None,
142        };
143        assert_eq!(
144            fr.download_url("http://localhost:2900", "default", "users"),
145            "http://localhost:2900/v1/files/default/users/f0001/123-t.png"
146        );
147        assert_eq!(fr.relative_url("default", "users"), "/v1/files/default/users/f0001/123-t.png");
148    }
149
150    #[test]
151    fn bound_file_ref_uses_table_context_for_urls() {
152        let fr = FileRef {
153            id: "123".into(),
154            sub: "f0001".into(),
155            name: "t.png".into(),
156            size: 0,
157            mime: "image/png".into(),
158            sha256: String::new(),
159            shard: None,
160        };
161        let ctx = FileRefContext::from_strings("default", "users");
162        let bound = BoundFileRef::new(fr, ctx);
163
164        assert_eq!(bound.namespace(), "default");
165        assert_eq!(bound.table(), "users");
166        assert_eq!(
167            bound.download_url("http://localhost:2900/"),
168            "http://localhost:2900/v1/files/default/users/f0001/123-t.png"
169        );
170        assert_eq!(bound.relative_url(), "/v1/files/default/users/f0001/123-t.png");
171        assert_eq!(bound.file_ref().name, "t.png");
172    }
173
174    #[test]
175    fn format_size_units() {
176        let mk = |size: u64| FileRef {
177            id: String::new(),
178            sub: String::new(),
179            name: String::new(),
180            size,
181            mime: String::new(),
182            sha256: String::new(),
183            shard: None,
184        };
185        assert_eq!(mk(0).format_size(), "0 B");
186        assert_eq!(mk(512).format_size(), "512 B");
187        assert_eq!(mk(1024).format_size(), "1.0 KB");
188        assert_eq!(mk(1_048_576).format_size(), "1.0 MB");
189    }
190
191    #[test]
192    fn stored_name_and_path() {
193        let fr = FileRef {
194            id: "42".into(),
195            sub: "f0001".into(),
196            name: "My Document.pdf".into(),
197            size: 100,
198            mime: "application/pdf".into(),
199            sha256: String::new(),
200            shard: None,
201        };
202        assert_eq!(fr.stored_name(), "42-my-document.pdf");
203        assert_eq!(fr.relative_path(), "f0001/42-my-document.pdf");
204    }
205
206    #[test]
207    fn stored_name_with_shard() {
208        let fr = FileRef {
209            id: "42".into(),
210            sub: "f0001".into(),
211            name: "test.png".into(),
212            size: 100,
213            mime: "image/png".into(),
214            sha256: String::new(),
215            shard: Some(3),
216        };
217        assert_eq!(fr.relative_path(), "shard-3/f0001/42-test.png");
218    }
219
220    #[test]
221    fn cell_as_file() {
222        use super::super::kalam_cell_value::KalamCellValue;
223
224        let cell = KalamCellValue::from(serde_json::json!({
225            "id": "1", "sub": "f0001", "name": "a.png",
226            "size": 10, "mime": "image/png", "sha256": "x"
227        }));
228        let fr = cell.as_file().unwrap();
229        assert_eq!(fr.id, "1");
230        assert!(fr.is_image());
231
232        assert!(KalamCellValue::text("Alice").as_file().is_none());
233        assert!(KalamCellValue::null().as_file().is_none());
234    }
235
236    #[test]
237    fn cell_as_bound_file_attaches_context() {
238        use super::super::kalam_cell_value::KalamCellValue;
239
240        let cell = KalamCellValue::from(serde_json::json!({
241            "id": "1", "sub": "f0001", "name": "a.png",
242            "size": 10, "mime": "image/png", "sha256": "x"
243        }));
244
245        let table_id = TableId::from_strings("docs", "files");
246        let bound = cell.as_bound_file(&table_id).expect("FILE column");
247        assert_eq!(bound.namespace(), "docs");
248        assert_eq!(bound.table(), "files");
249        assert_eq!(bound.table_id(), &table_id);
250        assert_eq!(bound.file_ref().id, "1");
251        assert_eq!(bound.relative_url(), "/v1/files/docs/files/f0001/1-a.png");
252    }
253}