Skip to content

Refactor client tests, deprecate addProtocolIfNotPresent, fix abort bug, adjust documentation #1926

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

flevi29
Copy link
Collaborator

@flevi29 flevi29 commented Apr 21, 2025

Pull Request

Related issue

Fixes #1922

What does this PR do?

  • fixes bug where the wrong abort controller is passed to fetch
  • adjusts documentation
  • deprecates missing protocol in provided host
  • refactors tests

Summary by CodeRabbit

  • Refactor

    • Improved header management and timeout handling for HTTP requests.
    • Simplified and clarified internal documentation comments.
    • Enhanced URL protocol handling and removed deprecated utility functions.
  • Bug Fixes

    • Improved error handling for task timeouts to prevent unexpected errors.
  • Tests

    • Added new tests for health, stats, version, network, and core client functionality.
    • Removed outdated or redundant test suites to streamline testing.

@flevi29 flevi29 added the bug Something isn't working label Apr 21, 2025
Copy link

codecov bot commented Apr 21, 2025

Codecov Report

Attention: Patch coverage is 84.21053% with 6 lines in your changes missing coverage. Please review.

Project coverage is 98.07%. Comparing base (77505c0) to head (e75b4d2).

Files with missing lines Patch % Lines
src/utils.ts 33.33% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1926      +/-   ##
==========================================
- Coverage   99.03%   98.07%   -0.96%     
==========================================
  Files          18       18              
  Lines        1449     1456       +7     
  Branches      305      304       -1     
==========================================
- Hits         1435     1428       -7     
- Misses         14       28      +14     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@flevi29 flevi29 marked this pull request as ready for review April 25, 2025 07:36
Copy link

coderabbitai bot commented May 19, 2025

Walkthrough

This update refactors internal utility usage, replaces string literals with constants for headers and agent strings, and improves timeout and abort logic. It removes the addTrailingSlash utility, normalizes host URLs inline, and updates error handling in task waiting. Several test files are reorganized, with comprehensive new tests added and outdated ones removed.

Changes

File(s) Change Summary
src/http-requests.ts, src/utils.ts Removed addTrailingSlash utility; normalized host URLs inline. Replaced header string literals with constants. Improved timeout and abort logic. Updated error handling and code clarity.
src/task.ts Updated error handling in waitForTask to use optional chaining for the error cause property.
src/types/types.ts Clarified and condensed documentation comments in the Config type. No type changes.
tests/client.test.ts, tests/errors.test.ts Deleted outdated test suites covering client instantiation, error handling, and end-to-end scenarios.
tests/health.test.ts, tests/meilisearch.test.ts, tests/network.test.ts, tests/stats.test.ts, tests/version.test.ts Added new test suites for health, network, stats, version, and comprehensive MeiliSearch client behaviors, including error and timeout handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpRequests
    participant Fetch/HTTP
    participant AbortController

    Client->>HttpRequests: sendRequest(options)
    HttpRequests->>AbortController: create signal (with timeout)
    HttpRequests->>Fetch/HTTP: fetch(url, { signal, headers })
    alt Timeout occurs
        AbortController-->>Fetch/HTTP: abort signal
        Fetch/HTTP-->>HttpRequests: throws AbortError
        HttpRequests-->>Client: throws MeiliSearchRequestTimeOutError
    else Success
        Fetch/HTTP-->>HttpRequests: response
        HttpRequests-->>Client: response
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Abort search when reaching timeout (#1922) Timeout abort logic was improved to correctly handle request abortion and propagate timeout errors.

Poem

Oh, what a hop through the code we have made,
Old slashes and strings in the shadows now fade.
Constants stand tall where literals once lay,
Timeouts and errors now handled the rabbit way.
With tests refreshed and logic anew,
This bunny is proud of the work we now do!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 519a27f and e75b4d2.

📒 Files selected for processing (1)
  • src/http-requests.ts (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/http-requests.ts

🪧 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 sequence diagram to generate a sequence diagram of the changes in 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

@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: 1

🧹 Nitpick comments (2)
src/http-requests.ts (2)

86-86: Consider replacing void with undefined in union type

The static analysis tool correctly flagged that void can be confusing in a union type. Consider using undefined instead for clarity.

-): () => (() => void) | void {
+): () => (() => void) | undefined {
🧰 Tools
🪛 Biome (1.9.4)

[error] 86-86: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


40-40: Fix typo in constant name

The constant PACAKGE_AGENT contains a typo - it should be PACKAGE_AGENT.

-const PACAKGE_AGENT = `Meilisearch JavaScript (v${PACKAGE_VERSION})`;
+const PACKAGE_AGENT = `Meilisearch JavaScript (v${PACKAGE_VERSION})`;

Also update the references to this constant:

-    const agents = config.clientAgents.concat(PACAKGE_AGENT);
+    const agents = config.clientAgents.concat(PACKAGE_AGENT);
-    headers.set(AGENT_HEADER_KEY, PACAKGE_AGENT);
+    headers.set(AGENT_HEADER_KEY, PACKAGE_AGENT);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 77505c0 and 519a27f.

📒 Files selected for processing (11)
  • src/http-requests.ts (7 hunks)
  • src/task.ts (1 hunks)
  • src/types/types.ts (3 hunks)
  • src/utils.ts (1 hunks)
  • tests/client.test.ts (0 hunks)
  • tests/errors.test.ts (0 hunks)
  • tests/health.test.ts (1 hunks)
  • tests/meilisearch.test.ts (1 hunks)
  • tests/network.test.ts (1 hunks)
  • tests/stats.test.ts (1 hunks)
  • tests/version.test.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • tests/errors.test.ts
  • tests/client.test.ts
🧰 Additional context used
🧬 Code Graph Analysis (4)
tests/health.test.ts (1)
tests/utils/meilisearch-test-utils.ts (2)
  • getClient (258-258)
  • assert (131-134)
tests/version.test.ts (1)
tests/utils/meilisearch-test-utils.ts (2)
  • getClient (258-258)
  • assert (131-134)
tests/stats.test.ts (1)
tests/utils/meilisearch-test-utils.ts (2)
  • getClient (258-258)
  • assert (131-134)
tests/network.test.ts (2)
tests/utils/meilisearch-test-utils.ts (2)
  • getClient (258-258)
  • assert (131-134)
src/types/types.ts (1)
  • Remote (292-295)
🪛 Biome (1.9.4)
src/http-requests.ts

[error] 86-86: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: integration-tests (Node.js 20)
  • GitHub Check: integration-tests (Node.js 22)
  • GitHub Check: integration-tests (Node.js 18)
🔇 Additional comments (24)
src/utils.ts (4)

5-5: Good addition for managing warning state.

Adding a static boolean flag to track whether the warning has been dispatched is a good approach. This ensures the deprecation warning only appears once per runtime, preventing console spam.


7-9: Nice improvement with regex pattern matching.

Replacing multiple string checks with a single regex pattern is more maintainable and concise. The pattern /^https?:\/\// correctly matches both HTTP and HTTPS protocols.


11-16: Well-implemented deprecation warning.

The warning message clearly communicates that the automatic protocol addition feature is being deprecated. The single-dispatch implementation is a good user experience practice, and explicitly showing the host value in the message helps with debugging.


21-21: Proper export list update.

The export list has been updated to remove addTrailingSlash which aligns with its removal from the codebase. This ensures the exported API is consistent with the implementation.

tests/version.test.ts (2)

1-5: Good test setup with appropriate dependencies.

The test properly imports the necessary testing utilities and initializes a client with the required permissions. Using await at the top level is appropriate here for test setup.


6-13: Comprehensive version object validation.

This test effectively validates both the structure and types of the version response:

  1. Verifies the exact number of keys (3)
  2. Destructures to verify the expected property names exist
  3. Confirms each property is of type string

Using a loop for the type checks is an efficient approach.

tests/health.test.ts (2)

1-5: Well-structured test setup.

The setup follows the same pattern as other test files, promoting consistency across the test suite. The client is properly initialized with master permissions.


6-10: Effective health endpoint validation.

The test properly validates both:

  1. The structure of the health response (exactly one key)
  2. The expected status value ("available")

This ensures the health endpoint works as intended and maintains its API contract.

src/task.ts (1)

130-130: Important error handling improvement.

Adding optional chaining (?.) when accessing the cause property makes the error handling more robust by safely handling cases where:

  1. The error might not be an object
  2. The error might not have a cause property

This prevents potential "Cannot read property 'cause'" errors that would mask the original error.

src/types/types.ts (4)

48-49: Improved documentation clarity.

The documentation for the host property has been simplified to a clear, concise description.


57-59: Grammar correction in documentation.

Changed "concatted" to the grammatically correct "concatenated" in the documentation.


67-68: Minor documentation improvement.

Changed from "will have to be handled manually" to the more direct "have to be handled manually."


72-79: Enhanced timeout documentation with important implementation details.

Excellent addition of detailed documentation for the timeout property. The comments now explain that it uses setTimeout, which doesn't guarantee precise timing, and includes a link to MDN documentation about potential delays.

tests/stats.test.ts (1)

1-37: Well-structured comprehensive test for statistics functionality.

The test effectively validates both the structure and type correctness of the response from the getStats method. It verifies the top-level properties and iterates through each index's statistics to ensure they have the expected structure and types.

tests/network.test.ts (1)

17-48: Comprehensive test for network update and retrieval functionality.

The test effectively validates the behavior of both updateNetwork and getNetwork methods. It:

  • Creates a well-formed network configuration
  • Defines a thorough validation function for remote entries
  • Verifies the response structure from both methods
  • Ensures consistency between the updated and retrieved network configurations
tests/meilisearch.test.ts (4)

20-124: Excellent comprehensive abort and timeout handling tests.

This test suite thoroughly examines request abortion scenarios, including:

  • Global timeout handling
  • Explicit abort signal handling
  • Interactions between global timeouts and signal timeouts
  • Proper error propagation with expected causes

The tests ensure that the abort controller behavior works correctly in all scenarios, which addresses the bug mentioned in the PR objectives related to incorrect abort controller handling.


126-185: Thorough header composition and priority testing.

This test effectively verifies that headers from multiple sources (API key, client agents, global headers, and custom headers) are correctly combined with the expected precedence. It checks specific headers like authorization and client identification headers, as well as the overall header structure.


187-200: Good verification of custom HTTP client functionality.

The test confirms that a custom HTTP client function is properly called with the expected parameters, including verifying that the URL passed to the client is correctly constructed based on the configured host.


202-255: Comprehensive error handling tests.

This test suite thoroughly covers the three main error types:

  1. MeiliSearchError for configuration errors (invalid host)
  2. MeiliSearchRequestError for network-level errors
  3. MeiliSearchApiError for API response errors

Each test verifies that the correct error type is thrown with the expected properties, ensuring robust error handling.

src/http-requests.ts (5)

37-40: LGTM: Good refactoring with constants

Replacing string literals with named constants improves maintainability and reduces the risk of typos. This is a good practice.


84-91: Fixed abort controller bug

This change ensures the correct abort controller signal is passed to the fetch function, addressing the bug mentioned in the PR objectives.

🧰 Tools
🪛 Biome (1.9.4)

[error] 86-86: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


113-115: Improved abort handling with clear timeout identification

The use of TIMEOUT_ID as the abort reason makes it easier to identify timeout-specific aborts, improving error handling clarity.

Also applies to: 134-136


152-152: Good replacement for addTrailingSlash

This inline check for trailing slash and conditional addition is a clean replacement for the removed utility function.


16-16:

✅ Verification successful

Confirm deprecation implementation of addProtocolIfNotPresent

This aligns with the PR objective to deprecate automatic protocol addition. Make sure that the implementation of this function in utils.js contains appropriate deprecation warnings.


🏁 Script executed:

#!/bin/bash
# Check if addProtocolIfNotPresent has deprecation warnings
grep -A 10 "addProtocolIfNotPresent" src/utils.js || grep -A 10 "addProtocolIfNotPresent" src/utils.ts

Length of output: 506


Deprecation warning in addProtocolIfNotPresent confirmed
The implementation in src/utils.ts already logs a one-time deprecation warning via console.warn guarded by warningDispatched. No further action needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Search should be aborted when reaching timeout
1 participant