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

feat(js-dapi-client): add contested resources query methods #2446

Open
wants to merge 2 commits into
base: v2.0-dev
Choose a base branch
from

Conversation

pshenmic
Copy link
Collaborator

@pshenmic pshenmic commented Jan 26, 2025

Issue being fixed or feature implemented

JS DAPI Client is missing methods for querying contested resources info, that is used to retrieve current contested documents and vote resource state info.

Backport from https://github.com/owl352/dapi-client

What was done?

How Has This Been Tested?

Breaking Changes

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • New Features

    • Added methods to retrieve contested resource vote states
    • Added methods to fetch contested resources
    • Introduced new response classes for handling contested resource queries
  • Improvements

    • Implemented robust error handling and retry mechanisms for resource queries
    • Enhanced platform methods facade with new query capabilities

@pshenmic pshenmic added the js-sdk JS Dash SDK related label Jan 26, 2025
@pshenmic pshenmic self-assigned this Jan 26, 2025
Copy link
Contributor

coderabbitai bot commented Jan 26, 2025

Walkthrough

The changes introduce new functionality to the Dash Platform JavaScript client for interacting with contested resources and their vote states. Two new methods, getContestedResourceVoteState and getContestedResources, have been added to the PlatformMethodsFacade class. These methods allow developers to query information about contested resources, including their current vote status and details. The implementation includes factory functions, response classes, and comprehensive test coverage to ensure reliable interaction with the Dash Platform's gRPC transport layer.

Changes

File Change Summary
packages/js-dapi-client/lib/methods/platform/PlatformMethodsFacade.js Added two new methods: getContestedResourceVoteState and getContestedResources
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/GetContestedResourceVoteStateResponse.js New response class for handling contested resource vote state responses
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/getContestedResourceVoteStateFactory.js New factory function for creating contested resource vote state method
packages/js-dapi-client/lib/methods/platform/getContestedResources/getContestedResourcesFactory.js New factory function for creating contested resources retrieval method
packages/js-dapi-client/lib/methods/platform/getContestedResources/getContestedResourcesResponse.js New response class for handling contested resources responses
packages/js-dapi-client/test/unit/methods/platform/... Updated test files to cover new contested resources functionality

Sequence Diagram

sequenceDiagram
    participant Client
    participant PlatformMethodsFacade
    participant gRPCTransport
    participant ContestedResourcesService

    Client->>PlatformMethodsFacade: getContestedResources()
    PlatformMethodsFacade->>gRPCTransport: Create gRPC Request
    gRPCTransport->>ContestedResourcesService: Send Request
    ContestedResourcesService-->>gRPCTransport: Return Contested Resources
    gRPCTransport-->>PlatformMethodsFacade: Process Response
    PlatformMethodsFacade-->>Client: Return Contested Resources
Loading

Poem

🐰 Hop, hop, through contested lands we go,
Resources dancing, vote states in tow,
gRPC whispers secrets so bright,
Platform methods now shine with might!
A rabbit's code, precise and clean, 🌟
Dash's new feature, now unforeseen!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 5

🧹 Nitpick comments (8)
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/GetContestedResourceVoteStateResponse.js (1)

35-37: Enhance error message with more context

The error message could be more descriptive to help with debugging.

     if ((typeof contestedResourceContenders === 'undefined' || contestedResourceContenders === null) && !proof) {
-      throw new InvalidResponseError('Contested Resource Contenders data is not defined');
+      throw new InvalidResponseError('Contested Resource Contenders data is not defined and no proof was provided');
     }
packages/js-dapi-client/lib/methods/platform/getContestedResources/getContestedResourcesResponse.js (1)

6-11: Complete the JSDoc parameter documentation

The JSDoc is missing type information for several parameters.

   /**
-   * @param {object} contestedResourceContenders
-   * @param contestedResources
-   * @param resultCase
+   * @param {Object} contestedResources - The contested resources data
+   * @param {number} resultCase - The result case identifier
    * @param {Metadata} metadata
    * @param {Proof} [proof]
    */
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/getContestedResourceVoteStateFactory.js (1)

28-29: Fix typo in JSDoc return type

There's a typo in the return type annotation.

-   * @returns {Promise<gрetContestedResourceVoteStateResponse>}
+   * @returns {Promise<GetContestedResourceVoteStateResponse>}
packages/js-dapi-client/test/unit/methods/platform/getContestedResources/GetContestedResourcesResponse.spec.js (3)

42-46: Add test cases for edge cases.

The test setup looks good, but consider adding test cases for:

  • Empty contested resource values
  • Invalid/malformed contested resource values
  • Maximum size contested resource values

58-63: Consider testing with multiple contested resources.

Current test only verifies with empty string. Add test cases with multiple contested resources to ensure proper handling of arrays.


Line range hint 121-128: Add test for invalid metadata values.

While testing for undefined metadata, also consider testing for invalid metadata values (negative heights, invalid timestamps, etc.).

packages/js-dapi-client/test/unit/methods/platform/getContestedResources/getContestedResourcesFactory.spec.js (2)

34-48: Consider using test data factories.

Instead of hardcoding test values, consider creating test data factories for better maintainability and reusability.

-    contractIdBuffer = Buffer.from('11c70af56a763b05943888fa3719ef56b3e826615fdda2d463c63f4034cb861c', 'hex');
-    documentTypeName = 'domain';
-    indexName = 'normalizedLabel';
+    const testDataFactory = createTestDataFactory();
+    ({ contractIdBuffer, documentTypeName, indexName } = testDataFactory.createBasicTestData());

83-124: Add test cases for pagination and filtering.

Current test cases only cover basic scenarios. Add tests for:

  • Different count values
  • Different ordering
  • Various index value combinations
  • Edge cases in pagination

Also applies to: 126-178

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cbddb8d and 586519e.

📒 Files selected for processing (7)
  • packages/js-dapi-client/lib/methods/platform/PlatformMethodsFacade.js (2 hunks)
  • packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/GetContestedResourceVoteStateResponse.js (1 hunks)
  • packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/getContestedResourceVoteStateFactory.js (1 hunks)
  • packages/js-dapi-client/lib/methods/platform/getContestedResources/getContestedResourcesFactory.js (1 hunks)
  • packages/js-dapi-client/lib/methods/platform/getContestedResources/getContestedResourcesResponse.js (1 hunks)
  • packages/js-dapi-client/test/unit/methods/platform/getContestedResources/GetContestedResourcesResponse.spec.js (4 hunks)
  • packages/js-dapi-client/test/unit/methods/platform/getContestedResources/getContestedResourcesFactory.spec.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build Docker images (DAPI, dapi, dapi) / Build DAPI image
  • GitHub Check: Build Docker images (Dashmate helper, dashmate-helper, dashmate-helper) / Build Dashmate helper image
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (3)
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/GetContestedResourceVoteStateResponse.js (1)

28-29: Add version compatibility check

The code assumes proto.getV0() exists without validation. This could lead to runtime errors if an incompatible version is received.

Add version check before accessing V0:

   static createFromProto(proto) {
+    if (!proto.hasV0()) {
+      throw new InvalidResponseError('Unsupported response version');
+    }
     const contestedResourceContenders = proto.getV0().getContestedResourceContenders();
packages/js-dapi-client/lib/methods/platform/getContestedResourceVoteState/getContestedResourceVoteStateFactory.js (1)

66-86: Improve retry mechanism

The retry implementation has the same issues as in getContestedResourcesFactory.

Please apply the same improvements suggested for the retry mechanism in getContestedResourcesFactory.js.

packages/js-dapi-client/lib/methods/platform/PlatformMethodsFacade.js (1)

19-20: LGTM! Clean integration of new methods.

The new methods are properly integrated following the established patterns in the codebase.

Also applies to: 47-48

}

return new GetContestedResourcesResponse(
contestedResourceContenders !== undefined ? contestedResourceContenders.getContestedResourceValuesList() : '',
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null check before accessing getContestedResourceValuesList

The code may throw if contestedResourceContenders is null but undefined check passes.

-      contestedResourceContenders !== undefined ? contestedResourceContenders.getContestedResourceValuesList() : '',
+      contestedResourceContenders != null ? contestedResourceContenders.getContestedResourceValuesList() : '',
📝 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
contestedResourceContenders !== undefined ? contestedResourceContenders.getContestedResourceValuesList() : '',
contestedResourceContenders != null ? contestedResourceContenders.getContestedResourceValuesList() : '',

Comment on lines +46 to +49
if (Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect Buffer conversion logic

The current implementation creates a new Buffer from an existing Buffer unnecessarily, and the condition is reversed.

-    if (Buffer.isBuffer(contractId)) {
+    if (!Buffer.isBuffer(contractId)) {
       // eslint-disable-next-line no-param-reassign
       contractId = Buffer.from(contractId);
     }
📝 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
if (Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}
if (!Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}

Comment on lines +66 to +86
// TODO: simple retry before the dapi versioning is properly implemented
for (let i = 0; i < 3; i += 1) {
try {
// eslint-disable-next-line no-await-in-loop
const getContestedResourcesResponse = await grpcTransport.request(
PlatformPromiseClient,
'getContestedResources',
getContestedResourcesRequest,
options,
);

return GetContestedResourcesResponse
.createFromProto(getContestedResourcesResponse);
} catch (e) {
if (e instanceof InvalidResponseError) {
lastError = e;
} else {
throw e;
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve retry mechanism

The retry implementation has several issues:

  1. Magic number for retry count
  2. No exponential backoff
  3. No delay between retries

Consider implementing a more robust retry mechanism:

+    const MAX_RETRIES = 3;
+    const BASE_DELAY = 1000; // 1 second
+
     // TODO: simple retry before the dapi versioning is properly implemented
-    for (let i = 0; i < 3; i += 1) {
+    for (let i = 0; i < MAX_RETRIES; i += 1) {
       try {
         // eslint-disable-next-line no-await-in-loop
         const getContestedResourcesResponse = await grpcTransport.request(
           PlatformPromiseClient,
           'getContestedResources',
           getContestedResourcesRequest,
           options,
         );
 
         return GetContestedResourcesResponse
           .createFromProto(getContestedResourcesResponse);
       } catch (e) {
         if (e instanceof InvalidResponseError) {
           lastError = e;
+          // Exponential backoff with jitter
+          const delay = Math.min(BASE_DELAY * Math.pow(2, i), 5000) + Math.random() * 1000;
+          await new Promise(resolve => setTimeout(resolve, delay));
         } else {
           throw e;
         }
       }
     }
📝 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
// TODO: simple retry before the dapi versioning is properly implemented
for (let i = 0; i < 3; i += 1) {
try {
// eslint-disable-next-line no-await-in-loop
const getContestedResourcesResponse = await grpcTransport.request(
PlatformPromiseClient,
'getContestedResources',
getContestedResourcesRequest,
options,
);
return GetContestedResourcesResponse
.createFromProto(getContestedResourcesResponse);
} catch (e) {
if (e instanceof InvalidResponseError) {
lastError = e;
} else {
throw e;
}
}
}
const MAX_RETRIES = 3;
const BASE_DELAY = 1000; // 1 second
// TODO: simple retry before the dapi versioning is properly implemented
for (let i = 0; i < MAX_RETRIES; i += 1) {
try {
// eslint-disable-next-line no-await-in-loop
const getContestedResourcesResponse = await grpcTransport.request(
PlatformPromiseClient,
'getContestedResources',
getContestedResourcesRequest,
options,
);
return GetContestedResourcesResponse
.createFromProto(getContestedResourcesResponse);
} catch (e) {
if (e instanceof InvalidResponseError) {
lastError = e;
// Exponential backoff with jitter
const delay = Math.min(BASE_DELAY * Math.pow(2, i), 5000) + Math.random() * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw e;
}
}
}

Comment on lines +46 to +49
if (Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect Buffer conversion logic

The Buffer conversion logic has the same issue as in getContestedResourcesFactory.

-    if (Buffer.isBuffer(contractId)) {
+    if (!Buffer.isBuffer(contractId)) {
       // eslint-disable-next-line no-param-reassign
       contractId = Buffer.from(contractId);
     }
📝 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
if (Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}
if (!Buffer.isBuffer(contractId)) {
// eslint-disable-next-line no-param-reassign
contractId = Buffer.from(contractId);
}

Comment on lines +70 to +72
grpcTransportMock = {
request: this.sinon.stub().resolves(response),
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling test cases.

The current test suite lacks test cases for error scenarios. Consider adding tests for:

  • Network errors
  • Invalid responses
  • Timeout scenarios

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js-sdk JS Dash SDK related
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant