| 1 | //! BlobStore:原始文件字节的存取接缝。 |
| 2 | //! |
| 3 | //! 内容寻址——key 就是文件内容的 sha256,接口里没有"路径"概念:本地是分桶前的 |
| 4 | //! 平铺目录、对象存储是 object key,任何 KV 都能实现。幂等、去重、不可变 |
| 5 | //! (内容变了指纹就变,旧版永不覆盖——"版本回放有料"的物质基础)全部由 |
| 6 | //! "内容即地址"免费获得。 |
| 7 | //! |
| 8 | //! 现阶段唯一实现是本地磁盘(data/files/{sha256})。将来接对象存储/网盘 |
| 9 | //! (P5 连接器、多实例部署共享存储)只需新增实现,摄入/上传/解析/回放的 |
| 10 | //! 调用方一行不改。配置入口 UTOPIA_BLOB_BACKEND 预留,当前仅接受 "local"。 |
| 11 | |
| 12 | use std::path::PathBuf; |
| 13 | |
| 14 | #[async_trait::async_trait] |
| 15 | pub trait BlobStore: Send + Sync { |
| 16 | /// 幂等写入:同指纹已存在即跳过。 |
| 17 | async fn put(&self, sha256: &str, bytes: &[u8]) -> anyhow::Result<()>; |
| 18 | async fn get(&self, sha256: &str) -> anyhow::Result<Vec<u8>>; |
| 19 | #[allow(dead_code)] // 接口完整性:回放/GC 路径的将来消费者 |
| 20 | async fn exists(&self, sha256: &str) -> anyhow::Result<bool>; |
| 21 | } |
| 22 | |
| 23 | /// 本地磁盘实现:`{dir}/{sha256}` 平铺存放(与历史行为逐字节一致)。 |
| 24 | pub struct LocalBlobStore { |
| 25 | dir: PathBuf, |
| 26 | } |
| 27 | |
| 28 | impl LocalBlobStore { |
| 29 | pub fn new(dir: PathBuf) -> Self { |
| 30 | Self { dir } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[async_trait::async_trait] |
| 35 | impl BlobStore for LocalBlobStore { |
| 36 | async fn put(&self, sha256: &str, bytes: &[u8]) -> anyhow::Result<()> { |
| 37 | tokio::fs::create_dir_all(&self.dir).await?; |
| 38 | let path = self.dir.join(sha256); |
| 39 | if !path.exists() { |
| 40 | tokio::fs::write(&path, bytes).await?; |
| 41 | } |
| 42 | Ok(()) |
| 43 | } |
| 44 | |
| 45 | async fn get(&self, sha256: &str) -> anyhow::Result<Vec<u8>> { |
| 46 | Ok(tokio::fs::read(self.dir.join(sha256)).await?) |
| 47 | } |
| 48 | |
| 49 | async fn exists(&self, sha256: &str) -> anyhow::Result<bool> { |
| 50 | Ok(self.dir.join(sha256).exists()) |
| 51 | } |
| 52 | } |