cloudflare / cloudflare/pingora

Can the `BackgroundService` support a `&mut self` reference?

Open
#465 1 comment 0 reactions 0 assignees View on GitHub
ergonomics
Dominant language
Rust
Stars
27.4k
Forks
1.7k
Avg merge
6h 22m
Merged PRs (30d)
3

Description

## What is the problem your feature solves, or the need it fulfills?

The current signature of the start method in the `BackgroundService` trait is as follows.:
https://github.com/cloudflare/pingora/blob/bdb13a7e40b19280d703ad1f64abc29ee5baf480/pingora-core/src/services/background.rs#L31-L37

The `self` parameter is immutable. Currently, I have a function that needs to run in the background and requires `&mut self`. The scenario is quite simple: it involves consuming from a channel, but because `self` is immutable, it cannot perform `recv`. Here’s an example of the code:

```rust
#[async_trait]
impl BackgroundService for Observer {
async fn start(&self, mut shutdown: pingora::server::ShutdownWatch) {
let mut traces = Vec::with_capacity(self.batch_size);
let mut interval = tokio::time::interval(self.flush_interval);

loop {
tokio::select! {
_ = interval.tick() => {
if !traces.is_empty() {
// self.flush(&traces).await;
traces.clear();
}
}
trace = self.rx.recv() => {
if let Some(trace) = trace {
traces.push(trace);
if traces.len() >= self.batch_size {
// self.flush(&traces).await;
traces.clear();
}
}
}
_ = shutdown.changed() => {
if !traces.is_empty() {
// self.flush(&traces).await;
}
break;
}
}
}

todo!()
}
}
```

The following code shows that when the upper method calls `start`, `self` is `&mut self`. However, when it comes to the `start` method, `self` becomes `&self`, and these two signatures are not quite consistent. Is there a specific reason for this? I hope you can help clarify this for me. Thank you very much.

https://github.com/cloudflare/pingora/blob/bdb13a7e40b19280d703ad1f64abc29ee5baf480/pingora-core/src/services/background.rs#L66-L76

## Describe the solution you'd like

**Is it possible to change the method signature from `&self` to `&mut self`?**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.