返回首页
最新
嗨,HN,
我正在实验一个 Rust 运行时,它通过广告一个 *过程宏* 来暴露 <i>复制的、基于共识的状态</i>。客户端库调用这个宏并获得一个类型化的 API;运行时同时拥有协议和代码生成。
从高层次来看,数据库单元:
* 处理 RPC(插入/获取/删除)
* 协调客户端 API 的宏扩展
* 存储不透明的零拷贝二进制数据(`rkyv`)
以下是数据库端的核心代码:
```rust
use cell_sdk::<i>;
use cell_model::macro_coordination::</i>;
use std::pin::Pin;
#[protein]
pub struct Upsert {
pub key: u64,
pub kind: String,
pub blob: Vec<u8>,
}
#[protein]
pub struct Get { pub key: u64, pub kind: String }
#[protein]
pub struct Row { pub blob: Option<Vec<u8>> }
#[service]
#[derive(Clone)]
struct DbService {
state: Arc<RwLock<HashMap<(u64, String), Vec<u8>>>>,
}
#[handler]
impl DbService {
async fn upsert(&self, u: Upsert) -> Result<bool> {
self.state.write().await.insert((u.key, u.kind), u.blob);
Ok(true)
}
async fn get(&self, g: Get) -> Result<Row> {
let val = self.state.read().await.get(&(g.key, g.kind)).cloned();
Ok(Row { blob: val })
}
async fn remove(&self, k: u64, kind: String) -> Result<bool> {
Ok(self.state.write().await.remove(&(k, kind)).is_some())
}
}
fn expand_table(ctx: &ExpansionContext) -> Pin<Box<dyn Future<Output=Result<String>> + Send + '_>> {
Box::pin(async move {
let struct_name = &ctx.struct_name;
let pk = ctx.fields.first().unwrap().0.clone();
Ok(format!(r#"
pub struct {struct_name}Table {{ synapse: ::cell_sdk::Synapse }}
impl {struct_name}Table {{
pub async fn connect() -> ::anyhow::Result<Self> {{
Ok(Self {{ synapse: ::cell_sdk::Synapse::grow("db").await? }})
}}
pub async fn save(&self, row: {struct_name}) -> ::anyhow::Result<bool> {{
let bytes = ::cell_sdk::rkyv::to_bytes::<_,1024>(&row)?.into_vec();
let req = DbProtocol::Upsert {{
key: row.{pk},
kind: "{struct_name}".into(),
blob: bytes,
}};
self.synapse.fire(&req).await
}}
}}
"#))
})
}
#[tokio::main]
async fn main() -> Result<()> {
let db = DbService { state: Default::default() };
const macros = vec![MacroInfo {
name: "table".into(),
kind: MacroKind::Attribute,
description: "distributed table".into(),
dependencies: vec![],
}];
Runtime::ignite_with_coordination(
move |req| db.dispatch(req),
"db",
macros,
expand_table,
).await
}
```
消费者代码:
```rust
use cell_sdk::<i>;
#[expand("db", "table")]
#[derive(Archive, Serialize, Clone, Debug)]
pub struct Order {
pub order_id: u64,
pub user_id: u64,
pub amount: u64,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let orders = OrderTable::connect().await?;
orders.save(Order { order_id: 42, user_id: 7, amount: 1000 }).await?;
let o = orders.get(42).await?.unwrap();
println!("loaded {o:?}");
orders.remove(42).await?;
Ok(())
}
```
问题是:*让一个分布式服务同时拥有其协议和客户端侧的宏是否合理,还是说这隐藏了太多复杂性?*
还有:这对企业是否真的有用?你会使用它吗?
谢谢 — 我在寻找设计层面的反馈,而不是用户。
我制作了一个模拟场景,你将扮演一位在忏悔室的神父,不同的语言模型(LLMs)会向你忏悔他们在道德情境中犯下的错误,而你可以选择原谅他们。<p>这个想法受到另一篇文章中评论的启发。相关内容:训练语言模型以诚实为目标 <a href="https://news.ycombinator.com/item?id=46242795">https://news.ycombinator.com/item?id=46242795</a>