Skip to content

Use tokio sleep instead of blocking thread when using reqwest client #689

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 29, 2025

Conversation

paolobarbolini
Copy link
Contributor

@paolobarbolini paolobarbolini commented Jul 25, 2025

Pull Request

Related issue

None

What does this PR do?

This PR makes meilisearch-sdk use the much more efficient tokio sleep machinery when the reqwest HTTP client is used to make requests (we assume reqwest means that the user is using tokio because it only works with tokio) instead of spawing a new ad hoc blocking thread for each sleep request.

PR checklist

  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Summary by CodeRabbit

  • New Features
    • Improved handling of asynchronous sleep operations, dynamically selecting the sleep mechanism based on the runtime environment.
    • Enhanced compatibility with different platforms, supporting both Tokio-based and non-Tokio environments.
  • Bug Fixes
    • More reliable sleep behavior across various platforms and runtimes.
  • Tests
    • Added and updated tests to ensure correct sleep functionality for each supported backend.

Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Walkthrough

The changes introduce a new abstraction, SleepBackend, to handle asynchronous sleeping across different platforms and runtimes. The codebase now dynamically selects the appropriate sleep mechanism (Tokio, thread, or JavaScript) based on the runtime environment and features. Associated traits and implementations are updated to support this abstraction, and dependencies are adjusted accordingly.

Changes

Cohort / File(s) Change Summary
Dependency Management
Cargo.toml
Added tokio as an optional dependency with the "time" feature; updated reqwest feature list to include dep:tokio.
Client Logic
src/client.rs
Replaced direct sleep calls with SleepBackend abstraction; added a private method to infer backend based on HTTP client runtime.
HttpClient Trait
src/request.rs
Added is_tokio method with default false implementation to HttpClient trait.
Reqwest Implementation
src/reqwest.rs
Implemented is_tokio method returning true for ReqwestClient.
Sleep Abstraction and Utilities
src/utils.rs
Removed async_sleep function; introduced SleepBackend enum with variants for Tokio, Thread, and Javascript; added infer and async sleep methods; updated tests accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpClient
    participant SleepBackend

    Client->>HttpClient: is_tokio()
    Client->>SleepBackend: infer(is_tokio)
    loop while waiting for task
        Client->>SleepBackend: sleep(interval)
        SleepBackend-->>Client: (sleeps using Tokio, Thread, or JS)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Suggested labels

maintenance

Poem

In burrows deep, where code does creep,
A rabbit dreams of restful sleep.
With threads or Tokio, JS too,
It picks the backend right for you.
Now platform woes are left behind—
The code hops forward, well-designed!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b32767 and 6ef36ce.

📒 Files selected for processing (5)
  • Cargo.toml (2 hunks)
  • src/client.rs (3 hunks)
  • src/request.rs (1 hunks)
  • src/reqwest.rs (1 hunks)
  • src/utils.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/reqwest.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • Cargo.toml
  • src/request.rs
  • src/utils.rs
  • src/client.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: integration-tests
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/utils.rs (2)

36-43: Consider adding error handling for thread panics.

The current implementation could hang indefinitely if the spawned thread panics before sending the signal. Consider adding timeout or panic handling.

 Self::Thread => {
     let (sender, receiver) = futures_channel::oneshot::channel::<()>();
     std::thread::spawn(move || {
+        let _guard = std::panic::catch_unwind(|| {
             std::thread::sleep(interval);
+        });
         let _ = sender.send(());
     });
     let _ = receiver.await;
 }

45-60: Consider more robust error handling for JavaScript implementation.

The multiple unwrap() calls could cause panics in edge cases. Consider handling potential failures more gracefully, especially for the duration conversion which could overflow for very large durations.

 Self::Javascript => {
     use std::convert::TryInto;
     use wasm_bindgen_futures::JsFuture;

+    let timeout_ms: i32 = interval.as_millis().try_into()
+        .unwrap_or(i32::MAX);
+
     JsFuture::from(web_sys::js_sys::Promise::new(&mut |yes, _| {
-        web_sys::window()
-            .unwrap()
-            .set_timeout_with_callback_and_timeout_and_arguments_0(
-                &yes,
-                interval.as_millis().try_into().unwrap(),
-            )
-            .unwrap();
+        if let Some(window) = web_sys::window() {
+            let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
+                &yes,
+                timeout_ms,
+            );
+        }
     }))
     .await
-    .unwrap();
+    .unwrap_or_default();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f11ec55 and 1b32767.

📒 Files selected for processing (5)
  • Cargo.toml (2 hunks)
  • src/client.rs (3 hunks)
  • src/request.rs (1 hunks)
  • src/reqwest.rs (1 hunks)
  • src/utils.rs (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/reqwest.rs
  • src/request.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • Cargo.toml
  • src/client.rs
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/utils.rs (3)
src/reqwest.rs (3)
  • is_tokio (116-118)
  • new (24-51)
  • new (148-155)
src/request.rs (1)
  • is_tokio (105-107)
meilisearch-test-macro/src/lib.rs (1)
  • meilisearch_test (14-201)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: integration-tests
🔇 Additional comments (3)
src/utils.rs (3)

3-11: Well-structured enum with appropriate conditional compilation.

The SleepBackend enum design effectively abstracts over different sleep implementations based on target architecture and feature availability. The cfg conditions are logically structured to ensure the appropriate variant is available for each platform.


14-27: Inference logic correctly handles all platform and feature combinations.

The method properly selects the appropriate sleep backend based on target architecture, feature availability, and runtime detection. The conditional compilation ensures only relevant code paths are included for each target platform.


70-101: Comprehensive test coverage for all backend variants.

The tests effectively verify each sleep backend implementation with appropriate platform-specific conditional compilation. The timing assertions correctly validate that sleep duration is respected.

Copy link

codecov bot commented Jul 25, 2025

Codecov Report

❌ Patch coverage is 86.84211% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.67%. Comparing base (5dd4375) to head (6ef36ce).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
src/request.rs 0.00% 3 Missing ⚠️
src/utils.rs 92.85% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #689      +/-   ##
==========================================
- Coverage   85.76%   85.67%   -0.10%     
==========================================
  Files          19       19              
  Lines        5860     5883      +23     
==========================================
+ Hits         5026     5040      +14     
- Misses        834      843       +9     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Collaborator

@Mubelotix Mubelotix left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello! Thank you for your contribution. Our current implementation definitely needs to be improved. Your SleepBackend abstraction is interesting, but why would someone ever want to use the thread-blocking sleep? I would be in favor of just using tokio's sleep for everything except on wasm and removing the abstraction.

@paolobarbolini
Copy link
Contributor Author

paolobarbolini commented Jul 29, 2025

why would someone ever want to use the thread-blocking sleep

AFAIK your implementation, except for the reqwest support, is runtime agnostic. Having the reqwest feature make meilisearch-sdk always use tokio, even when the reqwest client isn't effectively being used, would be wrong because it would make the feature non-additive

@Mubelotix
Copy link
Collaborator

Thanks for the quick response! I still do not see why anyone would want to use the old thread-blocking sleep implementation. Tokio's sleep should always be best, so we can remove the old one. Also, that makes SleepBackend redundant. I think we just need an internal async fn sleep that uses tokio's sleep except for wasm target. The tokio dependency can be enabled for everyone unless on wasm

@paolobarbolini
Copy link
Contributor Author

paolobarbolini commented Jul 29, 2025

The below official code example would stop working because tokio sleep can only be used within a tokio runtime, so it's not compatible with the futures, async-std or smol runtimes to make a few examples.

block_on(async move {

Copy link
Collaborator

@Mubelotix Mubelotix left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh that's why, thank you for the clarification. Perfect then, nothing to improve

@Mubelotix Mubelotix merged commit c029adb into meilisearch:main Jul 29, 2025
9 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants