h3poteto / megalodon-rs

Fediverse API client library for Rust
Apache License 2.0
113 stars 24 forks source link

Keep reqwest client alive? #256

Open Lynnesbian opened 3 weeks ago

Lynnesbian commented 3 weeks ago

This is more of a query or a suggestion than an issue.

I noticed that this library creates a new reqwest::Client for each GET request: https://github.com/h3poteto/megalodon-rs/blob/5ebcaca720c3ec0e528b40461135ffa9e436e05c/src/mastodon/api_client.rs#L33-L45

Similar lines exist for POST requests, PUT requests, etc.

The reqwest docs recommend reusing the same client:

The Client holds a connection pool internally, so it is advised that you create one and reuse it. https://docs.rs/reqwest/0.12.9/reqwest/struct.Client.html

Note that Client makes use of Arc internally, making it safely cloneable.

I realise that there may be a reason for this behaviour. If that's the case, feel free to reply accordingly and close this issue.

Benefits

Aside from the entirely negligible performance increase of avoiding repeated calls to ClientBuilder::build(), reusing the same client allows reqwest to make use of HTTP's keep-alive feature:

NOTE: If you plan to perform multiple requests, it is best to create a Client and reuse it, taking advantage of keep-alive connection pooling. https://docs.rs/reqwest/latest/reqwest/#making-a-get-request

This would also allow Megalodon to store cookies, although I'm not sure if that's of any use - the Mastodon API doesn't use cookies, but the Fediverse is a vast and strange place. Maybe there's some API out there that requires cookies! :sweat_smile:

Implementation

I would be willing to open a pull request implementing this behaviour.

h3poteto commented 2 weeks ago

Ah, you're right. That's a good idea.