puetzp / prometheus-http-query

Prometheus HTTP API client
MIT License
14 stars 7 forks source link

Derive Clone on all response types #2

Closed nickmonad closed 2 years ago

nickmonad commented 2 years ago

First off, great project! This is exactly what I needed to help me implement a prometheus analysis tool I'm currently working on. I didn't see a CONTRIBUTING.md in the repo, so hopefully I'm checking all the boxes here.

I have a need to attach some response data types to custom structs, like so,

use prometheus_http_query::response;

struct Metric {
    name: String,
    metadata: response::MetricMetadata,
    rules: RefCell<Vec<Weak<Rule>>>,
}

struct Rule {
    metadata: response::Rule,
    metrics: RefCell<Vec<Rc<Metric>>>,
}

Without Clone on these response types, the following wouldn't be possible, since we can't "move" ownership out of the Vec<MetricMetadata> coming from the client, and dealing with references and lifetimes could get ugly real fast.

async fn load_metrics(client: &Client) -> anyhow::Result<HashMap<String, Rc<Metric>>> {
    Ok(HashMap::from_iter(
        client
            .metric_metadata(None, None)
            .await?
            .into_iter()
            .map(|(name, metadata)| {
                (
                    name.clone(),
                    Rc::new(Metric {
                        name: name.clone(),
                        metadata: metadata[0], // This isn't possible without `clone()`
                        rules: RefCell::new(vec![]),
                    }),
                )
            }),
    ))
}

I went ahead and just put #[derive(Clone)] on the types I needed to implement it, but if you want, I could also update all response types to derive Clone that can automatically do so.

cargo test passed locally with this change.

puetzp commented 2 years ago

Hey there, I agree, deriving Clone on every response type makes sense. It would be great if you could implement it for the remaining response types as well and I will merge it right after!

Also yeah, I should definitely add a CONTRIBUTING.md to the repository to pave the way for future contributions :)

nickmonad commented 2 years ago

@puetzp Awesome! I added #[derive(Clone)] to all response types