cloudflare / cloudflare/workers-rs
Usage of Router inside a DurableObject: need to move env, which is required to be a reference
- Dominant language
- Rust
- Stars
- 3.7k
- Forks
- 429
- Avg merge
- 20h 28m
- Merged PRs (30d)
- 7
Description
Hi,
Apologies in advance if I'm missing something obvious here, I'm new to Rust. I'm trying to use `Router` in a `#[durable_object]`s `fetch` method like so:
```rust
use worker::*;
#[durable_object]
pub struct Chatroom {
messages: Vec,
state: State,
env: Env,
}
#[durable_object]
impl DurableObject for Chatroom {
fn new(state: State, env: Env) -> Self {
Self {
messages: vec![],
state,
env,
}
}
async fn fetch(&mut self, req: Request) -> worker::Result {
let router = Router::with_data(&self.messages);
router
.get("/", |_req, context| {
Response::ok(&format!("{} messages", context.data().len()))
})
.run(req, self.env)
.await
}
}
```
This fails with the error:
```
error[E0507]: cannot move out of `self.env` which is behind a mutable reference
--> src/chatroom.rs:27:23
|
27 | .run(req, self.env)
| ^^^^^^^^ move occurs because `self.env` has type `worker::Env`, which does not implement the `Copy` trait
```
This makes sense to me, as `Router#run` takes ownership of it's `env` argument, and since I'm taking a `&mut self` as a reference I can't move `self.env`. The `#[durable_object]` macro forces `fetch` to be `&mut self` so I can _only_ give references of `env`. I can't work out how you would use Router inside it?
Contributor guide
Research direction
Start with the DurableObject fetch entry point shown in src/chatroom.rs, then inspect Router::with_data and Router::run to understand their ownership requirements. Verify the behavior with the displayed Chatroom example; done means a Router can be used from the mutable fetch method without moving the stored Env.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100