braid_http_rs 0.1.5

Unified Braid Protocol implementation in Rust, including Braid-HTTP, Antimatter CRDT, and BraidFS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use crate::core::traits::BraidStorage;
use crate::fs::mapping;
use crate::fs::state::DaemonState;
use async_trait::async_trait;
use nfsserve::nfs::{fattr3, ftype3, nfsstat3, nfsstring, nfstime3, sattr3, specdata3};
use nfsserve::tcp::NFSTcp;
use nfsserve::vfs::{DirEntry, NFSFileSystem, ReadDirResult, VFSCapabilities};
use parking_lot::RwLock as PRwLock;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tracing::info;
use url::Url;

/// Braid NFS backend implementation.
pub struct BraidNfsBackend {
    state: DaemonState,
    blob_store: Arc<crate::blob::BlobStore>,
    id_to_path: Arc<PRwLock<HashMap<u64, String>>>,
    path_to_id: Arc<PRwLock<HashMap<String, u64>>>,
    next_id: Arc<PRwLock<u64>>,
}

impl BraidNfsBackend {
    pub fn new(state: DaemonState, blob_store: Arc<crate::blob::BlobStore>) -> Self {
        let mut id_to_path = HashMap::new();
        let mut path_to_id = HashMap::new();

        // Root is ID 1
        id_to_path.insert(1, "/".to_string());
        path_to_id.insert("/".to_string(), 1);

        Self {
            state,
            blob_store,
            id_to_path: Arc::new(PRwLock::new(id_to_path)),
            path_to_id: Arc::new(PRwLock::new(path_to_id)),
            next_id: Arc::new(PRwLock::new(2)),
        }
    }

    fn get_path(&self, id: u64) -> Option<String> {
        self.id_to_path.read().get(&id).cloned()
    }

    fn get_or_create_id(&self, path: &str) -> u64 {
        let path = if path.is_empty() { "/" } else { path };
        if let Some(id) = self.path_to_id.read().get(path) {
            return *id;
        }
        let mut next_id = self.next_id.write();
        let id = *next_id;
        *next_id += 1;
        self.path_to_id.write().insert(path.to_string(), id);
        self.id_to_path.write().insert(id, path.to_string());
        id
    }

    fn get_attr(&self, id: u64, ftype: ftype3, size: u64) -> fattr3 {
        fattr3 {
            ftype,
            mode: if matches!(ftype, ftype3::NF3DIR) {
                0o755
            } else {
                0o644
            },
            nlink: 1,
            uid: 0,
            gid: 0,
            size,
            used: size,
            rdev: specdata3 {
                specdata1: 0,
                specdata2: 0,
            },
            fsid: 0,
            fileid: id,
            atime: nfstime3 {
                seconds: 0,
                nseconds: 0,
            },
            mtime: nfstime3 {
                seconds: 0,
                nseconds: 0,
            },
            ctime: nfstime3 {
                seconds: 0,
                nseconds: 0,
            },
        }
    }

    fn url_to_vpath(&self, url_str: &str) -> std::result::Result<String, anyhow::Error> {
        let url = Url::parse(url_str)?;
        let host = url
            .host_str()
            .ok_or_else(|| anyhow::anyhow!("URL missing host"))?;
        let port = url.port();
        let mut vpath = host.to_string();
        if let Some(p) = port {
            vpath.push_str(&format!("+{}", p));
        }
        for segment in url.path_segments().unwrap_or_else(|| "".split('/')) {
            if !segment.is_empty() {
                vpath.push('/');
                vpath.push_str(segment);
            }
        }
        if url.path().ends_with('/') {
            vpath.push_str("/index");
        }
        Ok(format!("/{}", vpath))
    }
}

#[async_trait]
impl NFSFileSystem for BraidNfsBackend {
    fn capabilities(&self) -> VFSCapabilities {
        VFSCapabilities::ReadOnly
    }

    fn root_dir(&self) -> u64 {
        1
    }

    async fn lookup(&self, parent_id: u64, name: &nfsstring) -> std::result::Result<u64, nfsstat3> {
        let parent_path = self.get_path(parent_id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let name_str = String::from_utf8_lossy(&name.0);

        // Handle virtual /blobs/ path
        let full_path = if parent_path == "/" && name_str == "blobs" {
            "/blobs".to_string()
        } else {
            mapping::path_join(&parent_path, &name_str)
        };

        Ok(self.get_or_create_id(&full_path))
    }

    async fn getattr(&self, id: u64) -> std::result::Result<fattr3, nfsstat3> {
        let vpath = self.get_path(id).ok_or(nfsstat3::NFS3ERR_STALE)?;

        // Special Case: Virtual /blobs directory
        if vpath == "/blobs" {
            return Ok(self.get_attr(id, ftype3::NF3DIR, 4096));
        }

        // Special Case: Files inside /blobs/
        if vpath.starts_with("/blobs/") {
            let key = &vpath["/blobs/".len()..];
            if let Ok(Some(meta)) = self.blob_store.get_meta(key).await {
                return Ok(self.get_attr(id, ftype3::NF3REG, meta.size.unwrap_or(0)));
            }
            // Fallback to checking disk or return error
        }

        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(vpath.trim_start_matches('/'));

        let metadata = tokio::fs::metadata(&path).await.ok();
        let (ftype, size) = if let Some(meta) = metadata {
            if meta.is_dir() {
                (ftype3::NF3DIR, 4096)
            } else {
                (ftype3::NF3REG, meta.len())
            }
        } else {
            let version_store = self.state.version_store.read().await;
            let is_vdir = version_store.file_versions.keys().any(|url| {
                if let Ok(vp) = self.url_to_vpath(url) {
                    vp.starts_with(&vpath) && vp != vpath
                } else {
                    false
                }
            });

            if is_vdir || vpath == "/" {
                (ftype3::NF3DIR, 4096)
            } else {
                return Err(nfsstat3::NFS3ERR_NOENT);
            }
        };

        Ok(self.get_attr(id, ftype, size))
    }

    async fn setattr(&self, _id: u64, _attr: sattr3) -> std::result::Result<fattr3, nfsstat3> {
        Err(nfsstat3::NFS3ERR_NOTSUPP)
    }

    async fn read(
        &self,
        id: u64,
        offset: u64,
        count: u32,
    ) -> std::result::Result<(Vec<u8>, bool), nfsstat3> {
        let vpath = self.get_path(id).ok_or(nfsstat3::NFS3ERR_STALE)?;

        // Special Case: Read from BlobStore
        if vpath.starts_with("/blobs/") {
            let key = &vpath["/blobs/".len()..];
            if let Ok(Some((data, _meta))) = self.blob_store.get(key).await {
                let start = offset as usize;
                if start >= data.len() {
                    return Ok((vec![], true));
                }
                let end = std::cmp::min(start + count as usize, data.len());
                let slice = &data[start..end];
                let eof = end == data.len();
                return Ok((slice.to_vec(), eof));
            }
            return Err(nfsstat3::NFS3ERR_NOENT);
        }

        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(vpath.trim_start_matches('/'));

        info!(
            "NFS Read: {} (vpath={}) offset={} count={}",
            path.display(),
            vpath,
            offset,
            count
        );

        if !path.exists() {
            return Err(nfsstat3::NFS3ERR_NOENT);
        }

        let mut file = tokio::fs::File::open(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        file.seek(std::io::SeekFrom::Start(offset))
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;

        let mut buffer = vec![0u8; count as usize];
        let n = file
            .read(&mut buffer)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        buffer.truncate(n);

        let eof = n < count as usize;
        Ok((buffer, eof))
    }

    async fn write(
        &self,
        id: u64,
        offset: u64,
        data: &[u8],
    ) -> std::result::Result<fattr3, nfsstat3> {
        let vpath = self.get_path(id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(vpath.trim_start_matches('/'));

        info!(
            "NFS Write: {} (vpath={}) offset={} len={}",
            path.display(),
            vpath,
            offset,
            data.len()
        );

        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        }

        let mut file = tokio::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        file.seek(std::io::SeekFrom::Start(offset))
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        file.write_all(data)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;

        let metadata = tokio::fs::metadata(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        Ok(self.get_attr(id, ftype3::NF3REG, metadata.len()))
    }

    async fn create(
        &self,
        dir_id: u64,
        name: &nfsstring,
        _attr: sattr3,
    ) -> std::result::Result<(u64, fattr3), nfsstat3> {
        let dir_path = self.get_path(dir_id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let name_str = String::from_utf8_lossy(&name.0).to_string();
        let full_path = mapping::path_join(&dir_path, &name_str);
        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(full_path.trim_start_matches('/'));

        info!("NFS Create: {} (vpath={})", path.display(), full_path);

        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        }

        tokio::fs::File::create(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;

        let id = self.get_or_create_id(&full_path);
        let attr = self.get_attr(id, ftype3::NF3REG, 0);
        Ok((id, attr))
    }

    async fn create_exclusive(
        &self,
        _dir_id: u64,
        _name: &nfsstring,
    ) -> std::result::Result<u64, nfsstat3> {
        Err(nfsstat3::NFS3ERR_NOTSUPP)
    }

    async fn mkdir(
        &self,
        dir_id: u64,
        name: &nfsstring,
    ) -> std::result::Result<(u64, fattr3), nfsstat3> {
        let dir_path = self.get_path(dir_id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let name_str = String::from_utf8_lossy(&name.0).to_string();
        let full_path = mapping::path_join(&dir_path, &name_str);
        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(full_path.trim_start_matches('/'));

        info!("NFS Mkdir: {} (vpath={})", path.display(), full_path);

        tokio::fs::create_dir_all(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;

        let id = self.get_or_create_id(&full_path);
        let attr = self.get_attr(id, ftype3::NF3DIR, 4096);
        Ok((id, attr))
    }

    async fn remove(&self, dir_id: u64, name: &nfsstring) -> std::result::Result<(), nfsstat3> {
        let dir_path = self.get_path(dir_id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let name_str = String::from_utf8_lossy(&name.0).to_string();
        let full_path = mapping::path_join(&dir_path, &name_str);
        let root = crate::fs::config::get_root_dir().map_err(|_| nfsstat3::NFS3ERR_IO)?;
        let path = root.join(full_path.trim_start_matches('/'));

        info!("NFS Remove: {} (vpath={})", path.display(), full_path);

        tokio::fs::remove_file(&path)
            .await
            .map_err(|_| nfsstat3::NFS3ERR_IO)?;
        Ok(())
    }

    async fn rename(
        &self,
        _old_dir: u64,
        _old_name: &nfsstring,
        _new_dir: u64,
        _new_name: &nfsstring,
    ) -> std::result::Result<(), nfsstat3> {
        Err(nfsstat3::NFS3ERR_NOTSUPP)
    }

    async fn readdir(
        &self,
        dir_id: u64,
        cookie: u64,
        _count: usize,
    ) -> std::result::Result<ReadDirResult, nfsstat3> {
        let dir_path = self.get_path(dir_id).ok_or(nfsstat3::NFS3ERR_STALE)?;
        let mut entries = Vec::new();

        if dir_path == "/" {
            // Add virtual /blobs entry
            let blob_id = self.get_or_create_id("/blobs");
            entries.push(DirEntry {
                fileid: blob_id,
                name: nfsstring("blobs".as_bytes().to_vec()),
                attr: self.get_attr(blob_id, ftype3::NF3DIR, 4096),
            });
        }

        if dir_path == "/blobs" {
            // List actual blobs from BlobStore
            if let Ok(keys) = Arc::clone(&self.blob_store).list_keys().await {
                for key in keys {
                    let full_path = format!("/blobs/{}", key);
                    let id = self.get_or_create_id(&full_path);
                    let size = self
                        .blob_store
                        .get_meta(&key)
                        .await
                        .ok()
                        .flatten()
                        .and_then(|m| m.size)
                        .unwrap_or(0);

                    entries.push(DirEntry {
                        fileid: id,
                        name: nfsstring(key.as_bytes().to_vec()),
                        attr: self.get_attr(id, ftype3::NF3REG, size),
                    });
                }
            }
        } else {
            let prefix = dir_path.clone();
            let version_store = self.state.version_store.read().await;
            let mut seen = std::collections::HashSet::new();

            for url in version_store.file_versions.keys() {
                if let Ok(vpath) = self.url_to_vpath(url) {
                    if vpath.starts_with(&prefix) && vpath != prefix {
                        let relative = if prefix == "/" {
                            &vpath[1..]
                        } else {
                            &vpath[prefix.len()..].trim_start_matches('/')
                        };
                        let segment = relative.split('/').next().unwrap_or("");
                        if !segment.is_empty() && seen.insert(segment.to_string()) {
                            let full_child_path = mapping::path_join(&dir_path, segment);
                            let child_id = self.get_or_create_id(&full_child_path);
                            let root = crate::fs::config::get_root_dir()
                                .map_err(|_| nfsstat3::NFS3ERR_IO)?;
                            let child_abs_path = root.join(full_child_path.trim_start_matches('/'));

                            let (ftype, size) = if child_abs_path.is_file() {
                                (
                                    ftype3::NF3REG,
                                    std::fs::metadata(&child_abs_path)
                                        .map(|m| m.len())
                                        .unwrap_or(0),
                                )
                            } else {
                                (ftype3::NF3DIR, 4096)
                            };

                            entries.push(DirEntry {
                                fileid: child_id,
                                name: nfsstring(segment.as_bytes().to_vec()),
                                attr: self.get_attr(child_id, ftype, size),
                            });
                        }
                    }
                }
            }
        }

        let start = cookie as usize;
        let paged_entries = if start < entries.len() {
            entries.into_iter().skip(start).collect()
        } else {
            vec![]
        };
        Ok(ReadDirResult {
            entries: paged_entries,
            end: true,
        })
    }

    async fn symlink(
        &self,
        _dir_id: u64,
        _name: &nfsstring,
        _target: &nfsstring,
        _attr: &sattr3,
    ) -> std::result::Result<(u64, fattr3), nfsstat3> {
        Err(nfsstat3::NFS3ERR_NOTSUPP)
    }

    async fn readlink(&self, _id: u64) -> std::result::Result<nfsstring, nfsstat3> {
        Err(nfsstat3::NFS3ERR_NOTSUPP)
    }
}