Skip to content
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

Fix web FetchRequest does not respect disableConnectivityCheck client option #1925

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

Conversation

VeskeR
Copy link
Contributor

@VeskeR VeskeR commented Nov 22, 2024

See internal slack thread for more context.

Summary by CodeRabbit

  • New Features

    • Enhanced connectivity check functionality, allowing for immediate success when the disableConnectivityCheck option is enabled.
  • Bug Fixes

    • Improved error handling for unsupported HTTP transports.
  • Tests

    • Expanded test coverage for browser connectivity scenarios, including new cases for disabled fetch and XHR request implementations.

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes in this pull request modify the checkConnectivity method within the Http class located in src/platform/web/lib/http/http.ts. The method now includes a conditional check for a disableConnectivityCheck option, altering its behavior based on this setting. Additionally, the connection.test.js file is updated to enhance testing for browser connectivity scenarios, incorporating new test cases that evaluate the connectivity checks when fetch and XHR implementations are disabled. The overall structure and public interface of the Http class remain unchanged.

Changes

File Path Change Summary
src/platform/web/lib/http/http.ts Modified checkConnectivity method to include a conditional check for disableConnectivityCheck. Ensured consistent behavior for both XHR and FetchRequest implementations.
test/browser/connection.test.js Added Ably module dependency and new test cases for connectivity checks when fetch and XHR are disabled. Enhanced overall test structure.

Possibly related PRs

Suggested reviewers

  • owenpearson
  • ttypic

Poem

🐰 In the web's vast, hopping space,
Connectivity checks now find their place.
With options set, they dance and play,
Fetch and XHR lead the way.
Tests now flourish, robust and bright,
Ensuring our paths stay clear and right! 🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint (1.23.1)

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

warning eslint@7.32.0: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/config-array@0.5.0: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/object-schema@1.2.1: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning grunt > glob@7.1.7: Glob versions prior to v9 are no longer supported
warning grunt > glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning grunt > grunt-cli > nopt > osenv@0.1.5: This package is no longer supported.
error eslint-plugin-jsdoc@40.3.0: The engine "node" is incompatible with this module. Expected version "^14 || ^16 || ^17 || ^18 || ^19". Got "22.9.0"
error Found incompatible module.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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: 3

🧹 Outside diff range and nitpick comments (1)
test/browser/connection.test.js (1)

458-458: Clarify the comment for better readability

The comment could be rephrased to more explicitly explain the purpose of these tests and how they differ from existing ones.

Suggested change:

- // this is identical to disable_connectivity_check test in connectivity, but here we specifically test browser supported request implementations
+ // Similar to the 'disable_connectivity_check' test in 'connectivity', but specifically testing browser-supported request implementations (XHR and Fetch)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 18a2559 and f4acc4a.

📒 Files selected for processing (2)
  • src/platform/web/lib/http/http.ts (1 hunks)
  • test/browser/connection.test.js (2 hunks)
🔇 Additional comments (3)
src/platform/web/lib/http/http.ts (2)

121-124: LGTM: Proper implementation of disableConnectivityCheck option

The implementation correctly respects the disableConnectivityCheck client option by immediately returning true when enabled, consistent with the XHR implementation.


120-138: Verify test coverage for connectivity checks

Let's ensure that the test suite adequately covers both XHR and Fetch implementations, particularly for custom connectivity check URLs.

✅ Verification successful

Let me gather more information about the test implementations to ensure proper coverage.


Let me check the actual test cases for both success and failure scenarios to ensure complete coverage.


Test coverage for connectivity checks is comprehensive

The test suite adequately covers all aspects of the connectivity check implementation:

  • Tests for both success and failure scenarios with custom URLs
  • Coverage for disableConnectivityCheck option
  • Specific tests for both XHR and Fetch implementations
  • Tests for connectivity check with different URL configurations

The changes in the connectivity check implementation are well-supported by existing tests.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for connectivity check related tests
echo "Searching for connectivity check related tests..."
rg -l "connectivityCheck|checkConnectivity" test/

# Search for custom URL configurations in tests
echo "Searching for custom connectivity URL configurations in tests..."
rg "connectivityCheckUrl" test/

Length of output: 1319


Script:

#!/bin/bash
# Check the connectivity test implementations
echo "Checking connectivity.test.js implementation:"
rg -A 10 "describe.*connectivity" test/realtime/connectivity.test.js

# Check transport test implementations
echo "Checking transport test implementations:"
rg -A 10 "describe.*connectivity" test/realtime/transports.test.js

# Check connection test implementations
echo "Checking connection test implementations:"
rg -A 10 "describe.*connectivity" test/browser/connection.test.js

# Look for disableConnectivityCheck usage in tests
echo "Checking disableConnectivityCheck usage:"
rg "disableConnectivityCheck" test/

Length of output: 2086


Script:

#!/bin/bash
# Check the specific test cases in connectivity tests
echo "Checking connectivity test cases:"
rg -B 2 -A 10 "it\(.*connectivity" test/realtime/connectivity.test.js

# Check the specific test cases in connection tests
echo "Checking connection test cases:"
rg -B 2 -A 10 "it\(.*connectivity" test/browser/connection.test.js

# Check for any XHR specific connectivity tests
echo "Checking XHR specific tests:"
rg -B 2 -A 10 "XHR.*connectivity|xhr.*connectivity" test/

Length of output: 2430

test/browser/connection.test.js (1)

3-3: Dependency Update: Added 'Ably' module to test dependencies

Including 'Ably' in the module dependencies ensures that the tests have access to Ably.Rest.Platform.Config, which is necessary for configuring and manipulating platform-specific settings in the new test scenarios.

Comment on lines +126 to +137
this.checkConnectivity = async function () {
Logger.logAction(
this.logger,
Logger.LOG_MICRO,
'(Fetch)Http.checkConnectivity()',
'Sending; ' + connectivityCheckUrl,
);
const requestResult = await this.doUri(HttpMethods.Get, connectivityCheckUrl, null, null, null);
const result = !requestResult.error && (requestResult.body as string)?.replace(/\n/, '') == 'yes';
Logger.logAction(this.logger, Logger.LOG_MICRO, '(Fetch)Http.checkConnectivity()', 'Result: ' + result);
return result;
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent handling of custom connectivity check URLs between XHR and Fetch implementations

The Fetch implementation doesn't handle custom connectivity check URLs (connectivityUrlIsDefault) in the same way as the XHR implementation. This could lead to different behaviors when using custom connectivity check URLs.

XHR implementation:

if (!connectivityUrlIsDefault) {
  result = !requestResult.error && isSuccessCode(requestResult.statusCode as number);
} else {
  result = !requestResult.error && (requestResult.body as string)?.replace(/\n/, '') == 'yes';
}

Fetch implementation only uses the body check:

const result = !requestResult.error && (requestResult.body as string)?.replace(/\n/, '') == 'yes';

Apply this diff to make the implementations consistent:

-          const result = !requestResult.error && (requestResult.body as string)?.replace(/\n/, '') == 'yes';
+          let result = false;
+          if (!connectivityUrlIsDefault) {
+            result = !requestResult.error && isSuccessCode(requestResult.statusCode as number);
+          } else {
+            result = !requestResult.error && (requestResult.body as string)?.replace(/\n/, '') == 'yes';
+          }

Comment on lines +458 to +479
for (const scenario of [
{
description: 'XHR request disable connectivity check',
ctx: { initialFetchSupported: Ably.Rest.Platform.Config.fetchSupported },
before: (ctx) => {
Ably.Rest.Platform.Config.fetchSupported = false;
},
after: (ctx) => {
Ably.Rest.Platform.Config.fetchSupported = ctx.initialFetchSupported;
},
},
{
description: 'Fetch request disable connectivity check',
ctx: { initialXhrSupported: Ably.Rest.Platform.Config.xhrSupported },
before: (ctx) => {
Ably.Rest.Platform.Config.xhrSupported = false;
},
after: (ctx) => {
Ably.Rest.Platform.Config.xhrSupported = ctx.initialXhrSupported;
},
},
]) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid mutating global configuration to prevent side effects in tests

Directly modifying global configurations like Ably.Rest.Platform.Config.fetchSupported and xhrSupported may lead to side effects affecting other tests, especially if tests are run in parallel. To prevent unintended interactions:

  • Use stubbing or mocking libraries (e.g., Sinon.js) to temporarily override these properties within the test scope.
  • Ensure that any modifications are safely isolated and restored, even if the test encounters an error.

Comment on lines +481 to +510
it(scenario.description, async function () {
const helper = this.test.helper;
scenario.before(scenario.ctx);

helper.recordPrivateApi('pass.clientOption.connectivityCheckUrl');
helper.recordPrivateApi('pass.clientOption.disableConnectivityCheck');
const options = {
connectivityCheckUrl: helper.unroutableHost,
disableConnectivityCheck: true,
autoConnect: false,
};

let thrownError = null;
let res = null;
try {
helper.recordPrivateApi('call.http.checkConnectivity');
res = await helper.AblyRealtime(options).http.checkConnectivity();
} catch (error) {
thrownError = error;
}

scenario.after(scenario.ctx);
expect(
res && !thrownError,
'Connectivity check completed ' +
(thrownError &&
(helper.recordPrivateApi('call.Utils.inspectError'), helper.Utils.inspectError(thrownError))),
).to.be.ok;
});
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper cleanup in tests by using 'finally' block or test hooks

If an exception occurs before scenario.after(scenario.ctx); is called, the global configurations may not be restored, potentially affecting other tests. To guarantee cleanup:

  • Place scenario.after(scenario.ctx); inside a finally block to ensure it executes regardless of errors.
  • Alternatively, use afterEach hooks provided by the testing framework to handle teardown.

Suggested change:

 try {
   helper.recordPrivateApi('call.http.checkConnectivity');
   res = await helper.AblyRealtime(options).http.checkConnectivity();
 } catch (error) {
   thrownError = error;
+} finally {
+  scenario.after(scenario.ctx);
 }
-scenario.after(scenario.ctx);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it(scenario.description, async function () {
const helper = this.test.helper;
scenario.before(scenario.ctx);
helper.recordPrivateApi('pass.clientOption.connectivityCheckUrl');
helper.recordPrivateApi('pass.clientOption.disableConnectivityCheck');
const options = {
connectivityCheckUrl: helper.unroutableHost,
disableConnectivityCheck: true,
autoConnect: false,
};
let thrownError = null;
let res = null;
try {
helper.recordPrivateApi('call.http.checkConnectivity');
res = await helper.AblyRealtime(options).http.checkConnectivity();
} catch (error) {
thrownError = error;
}
scenario.after(scenario.ctx);
expect(
res && !thrownError,
'Connectivity check completed ' +
(thrownError &&
(helper.recordPrivateApi('call.Utils.inspectError'), helper.Utils.inspectError(thrownError))),
).to.be.ok;
});
}
it(scenario.description, async function () {
const helper = this.test.helper;
scenario.before(scenario.ctx);
helper.recordPrivateApi('pass.clientOption.connectivityCheckUrl');
helper.recordPrivateApi('pass.clientOption.disableConnectivityCheck');
const options = {
connectivityCheckUrl: helper.unroutableHost,
disableConnectivityCheck: true,
autoConnect: false,
};
let thrownError = null;
let res = null;
try {
helper.recordPrivateApi('call.http.checkConnectivity');
res = await helper.AblyRealtime(options).http.checkConnectivity();
} catch (error) {
thrownError = error;
} finally {
scenario.after(scenario.ctx);
}
expect(
res && !thrownError,
'Connectivity check completed ' +
(thrownError &&
(helper.recordPrivateApi('call.Utils.inspectError'), helper.Utils.inspectError(thrownError))),
).to.be.ok;
});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant