> 作者:小黎的部落 | 日期:2026-10-30 | 系列:Rust 基础设施工具集

一、存储层的碎片化

在 Rust 项目中,数据存储是一个绕不开的话题。但不同场景需要不同的存储模型:

orca-persist 提供了这三种存储模型的统一抽象,外加快照恢复和 Schema 迁移能力。

二、核心设计

2.1 三种存储 Trait

// 键值存储
pub trait KvStore {
    async fn get(&self, key: &str) -> PersistResult<Option<String>>;
    async fn set(&self, key: &str, value: &str) -> PersistResult<()>;
    async fn delete(&self, key: &str) -> PersistResult<()>;
    async fn scan(&self, prefix: &str) -> PersistResult<Vec<(String, String)>>;
}

// 文档存储
pub trait DocumentStore<T: Serialize + DeserializeOwned> {
    async fn insert(&self, collection: &str, doc: &T) -> PersistResult<()>;
    async fn find(&self, collection: &str, predicate: impl Fn(&T) -> bool) -> PersistResult<Vec<T>>;
}

// 时序存储
pub trait TimeSeriesStore {
    async fn write(&self, metric: &str, value: f64, timestamp: i64) -> PersistResult<()>;
    async fn query_range(&self, metric: &str, from: i64, to: i64) -> PersistResult<Vec<(i64, f64)>>;
}

2.2 内存后端(开箱即用)

use orca_persist::{MemoryKvStore, MemoryDocumentStore, KvStore};

let store = MemoryKvStore::new();
store.set("user:1", r#"{"name":"Alice"}"#).await?;
let value = store.get("user:1").await?;

2.3 快照与恢复

use orca_persist::{Snapshot, MemoryKvStore};

let store = MemoryKvStore::new();
store.set("key1", "value1").await?;

// 创建快照
let snapshot = Snapshot::capture(&store).await?;
let data = snapshot.export()?;

// 从快照恢复
let new_store = MemoryKvStore::new();
Snapshot::restore(&new_store, &data).await?;

2.4 Schema 迁移

use orca_persist::Migration;

let migration = Migration::new("add_email_field")
    .version(2)
    .up(|store| Box::pin(async move {
        // 为所有用户添加 email 字段
        Ok(())
    }))
    .down(|store| Box::pin(async move {
        // 回滚
        Ok(())
    }));

migration.apply(&store).await?;

三、与其他方案对比

方案KV文档时序快照迁移Rust 原生
sled✅❌❌❌❌✅
SQLx❌✅❌❌✅✅
orca-persist✅✅✅✅✅✅

四、总结

orca-persist 的设计目标是:一套 API,三种存储模型,外加快照和迁移。它不替代专用数据库,而是为那些不需要完整数据库的场景提供一个轻量级的统一抽象。

五、下载

下载 orca-persist.tar.gz (18.2 KB)

← 返回文章列表