Diffinery

homeflare/celldpublic

38 lines · 1.3 KBRaw History
1use worker::*;
2
3// One Counter cell per /c/<name> path, same contract as worker/index.js —
4// but the increment happens in Rust compiled to Wasm.
5#[durable_object(fetch)]
6pub struct Counter {
7 state: State,
8}
9
10impl DurableObject for Counter {
11 fn new(state: State, _env: Env) -> Self {
12 Self { state }
13 }
14
15 async fn fetch(&self, req: Request) -> Result<Response> {
16 let n: u64 = self.state.storage().get("n").await.ok().flatten().unwrap_or(0);
17 let n = n + 1;
18 self.state.storage().put("n", &n).await?;
19 let path = req.path();
20 let name = path.strip_prefix("/c/").unwrap_or("");
21 Response::from_json(&serde_json::json!({ "name": name, "n": n, "lang": "rust" }))
22 }
23}
24
25#[event(fetch)]
26async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
27 let path = req.path();
28 if let Some(name) = path.strip_prefix("/c/").filter(|name| !name.is_empty()) {
29 let namespace = env.durable_object("COUNTER")?;
30 let stub = namespace.id_from_name(name)?.get_stub()?;
31 return stub.fetch_with_request(req).await;
32 }
33 let status = if path == "/" { 200 } else { 404 };
34 Ok(
35 Response::ok("celld rust demo. Try: curl http://localhost:8080/c/hello\n")?
36 .with_status(status),
37 )
38}