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

Handle stateful order replacement in Ender #1667

Merged
merged 11 commits into from
Jun 12, 2024

Conversation

chenyaoy
Copy link
Contributor

@chenyaoy chenyaoy commented Jun 11, 2024

Changelist

  • Add stateful order replacement handler to ender
  • Add tests
  • Change dydx_stateful_order_handler.sql to handle order replacement message

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • Bug Fixes

    • Corrected various typos and exception messages in order handling scripts.
  • New Features

    • Introduced stateful order replacement functionality, including placing and updating orders based on specific events.
  • Documentation

    • Updated test suite names for consistency.
  • Refactor

    • Enhanced SQL scripts to manage order status and placement scenarios more effectively.

@chenyaoy chenyaoy changed the title Chenyao/ender handle stateful order replacement Handle stateful order replacement in Ender Jun 11, 2024
Copy link
Contributor

coderabbitai bot commented Jun 11, 2024

Warning

Rate limit exceeded

@chenyaoy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 8 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 592b164 and 2a7d020.

Walkthrough

The recent changes introduce new functionalities and refinements to the stateful order handling within the indexer/services/ender module. Key updates include renaming a test suite for consistency, adding comprehensive test cases for stateful order replacements, and implementing the StatefulOrderReplacementHandler class. Additionally, SQL scripts have been updated to manage order replacement scenarios effectively.

Changes

Files/Paths Change Summary
.../stateful-order-placement-handler.test.ts Renamed test suite for consistency from 'statefulOrderPlacementHandler' to 'stateful-order-placement-handler'.
.../stateful-order-replacement-handler.test.ts Introduced test cases for handling stateful order replacements, including interactions with databases and Kafka messaging.
.../stateful-order-replacement-handler.ts Added StatefulOrderReplacementHandler class with methods to manage order replacements and generate Kafka events.
.../dydx_stateful_order_handler.sql Implemented order replacement functionality, updated order status, and refined processing of order attributes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant StatefulOrderReplacementHandler
    participant Database
    participant Kafka

    Client->>StatefulOrderReplacementHandler: Replace Order
    StatefulOrderReplacementHandler->>Database: Retrieve Order Details
    Database-->>StatefulOrderReplacementHandler: Order Details
    StatefulOrderReplacementHandler->>Database: Update Order Status
    StatefulOrderReplacementHandler->>Kafka: Produce Kafka Event
    Kafka-->>StatefulOrderReplacementHandler: Acknowledgment
    StatefulOrderReplacementHandler-->>Client: Order Replacement Confirmation
Loading

Poem

In the land of code, where orders flow,
A handler arose, to and fro.
With Kafka's whisper and SQL's might,
Orders replaced, set to flight.
Tests were written, clear and bright,
Ensuring all was done just right.
🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@@ -45,7 +45,7 @@ import { producer } from '@dydxprotocol-indexer/kafka';
import { ConditionalOrderPlacementHandler } from '../../../src/handlers/stateful-order/conditional-order-placement-handler';
import { createPostgresFunctions } from '../../../src/helpers/postgres/postgres-functions';

describe('conditionalOrderPlacementHandler', () => {
describe('conditional-order-placement-handler', () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

pnpm test -- {test_name} won't find the test if it's not the same as the file name

@chenyaoy chenyaoy requested review from tqin7 and dydxwill June 11, 2024 16:09
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8f0d3bc and 8ed0ebf.

Files selected for processing (10)
  • indexer/services/ender/tests/handlers/stateful-order/conditional-order-placement-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/stateful-order/conditional-order-triggered-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-placement-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-removal-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-replacement-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/helpers/constants.ts (1 hunks)
  • indexer/services/ender/tests/validators/stateful-order-validator.test.ts (3 hunks)
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (2 hunks)
  • indexer/services/ender/src/validators/stateful-order-validator.ts (6 hunks)
Files not summarized due to errors (1)
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql: Error: Server error. Please try again later.
Files skipped from review due to trivial changes (4)
  • indexer/services/ender/tests/handlers/stateful-order/conditional-order-placement-handler.test.ts
  • indexer/services/ender/tests/handlers/stateful-order/conditional-order-triggered-handler.test.ts
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-placement-handler.test.ts
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-removal-handler.test.ts
Additional context used
Biome
indexer/services/ender/src/validators/stateful-order-validator.ts

[error] 37-41: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 61-64: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 68-71: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 80-83: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 86-86: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 93-96: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 100-103: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 110-113: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 122-125: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 131-134: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 138-141: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 145-148: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 156-159: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 163-167: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 174-177: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 186-189: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 195-198: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 209-212: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 218-221: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 225-228: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

Additional comments not posted (7)
indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts (1)

28-104: The implementation of StatefulOrderReplacementHandler is robust and well-structured.

The class methods are well-defined and adhere to the expected functionalities of handling stateful order replacements. The use of async patterns and Kafka event generation is correctly implemented.

indexer/services/ender/__tests__/handlers/stateful-order/stateful-order-replacement-handler.test.ts (1)

42-221: Comprehensive test coverage for StatefulOrderReplacementHandler.

The tests adequately cover various scenarios including transaction and block events, ensuring that the handler behaves as expected under different conditions. The use of mocks and assertions is appropriate and helps validate the functionality effectively.

indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (1)

Line range hint 26-182: SQL script handles stateful order events effectively, including the new orderReplacement.

The script correctly handles different types of order events, ensuring that orders are processed based on their specific characteristics. The inclusion of orderReplacement is well-integrated into the existing logic.

indexer/services/ender/src/validators/stateful-order-validator.ts (1)

Line range hint 1-240: The StatefulOrderValidator class is well-implemented and covers all necessary validations.

The class methods are correctly structured to handle various stateful order events, ensuring that all necessary validations are performed. The use of detailed error messages enhances the clarity of the validation process.

Tools
Biome

[error] 209-212: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 218-221: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.


[error] 225-228: The function should not return a value because its return type is void. (lint/correctness/noVoidTypeReturn)

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

indexer/services/ender/__tests__/validators/stateful-order-validator.test.ts (2)

21-21: The addition of defaultStatefulOrderReplacementEvent is correctly implemented to support new test scenarios.


46-46: The addition of the test case for 'stateful order replacement' is well-implemented to ensure the new functionality behaves as expected under normal conditions.

indexer/services/ender/__tests__/helpers/constants.ts (1)

451-463: The definition of defaultStatefulOrderReplacementEvent is correctly implemented to facilitate testing of the stateful order replacement functionality. It includes necessary details like the old order ID and the new order configuration.

extends AbstractStatefulOrderHandler<StatefulOrderEventV1> {
eventType: string = 'StatefulOrderEvent';

public getOrderId(): string {
Copy link
Contributor

Choose a reason for hiding this comment

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

private?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated

},
));

if (config.SEND_SUBACCOUNT_WEBSOCKET_MESSAGE_FOR_STATEFUL_ORDERS) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think you can remove this config check - there's a bug with it anyways & it's not being used anywhere.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Got it, thanks for the context. Removed this if statement

@@ -141,5 +141,44 @@ BEGIN
ELSE
RAISE EXCEPTION 'Unkonwn sub-event type %', event_data;
END IF;

/* For order replacement, remove old order */
IF event_data->'orderReplacement' IS NOT NULL THEN
Copy link
Contributor

Choose a reason for hiding this comment

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

this code won't ever execute because of the earlier return statement on line 93.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you for catching! I fixed and adding the check for the old order tests that this is now working properly

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8ed0ebf and 7f9416c.

Files selected for processing (3)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-replacement-handler.test.ts (1 hunks)
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-replacement-handler.test.ts
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts
Additional comments not posted (3)
indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (3)

25-53: Handle order replacement with careful state management.

The addition of handling for orderReplacement is well-implemented. The logic to cancel the old order and update its status to 'CANCELED' before processing the new order ensures data consistency. However, ensure that the order_id and subaccount_id are validated before use to prevent potential issues from malformed input.


54-54: Reset order_record to prevent data carryover.

Resetting order_record to NULL after handling the order replacement is a good practice to ensure that subsequent operations do not inadvertently use stale data. This is crucial for maintaining the integrity of the function's operations.


Line range hint 57-84: Enhance handling of various order placements.

The expanded handling for different types of order placements (orderPlace, longTermOrderPlacement, conditionalOrderPlacement, orderReplacement) is comprehensive. The use of coalesce to select the first non-null order object is efficient. However, consider adding explicit null checks or validations for the fields accessed from order_ to ensure they are not null before use, which could lead to runtime errors.

let producerSendMock: jest.SpyInstance;

it.each([
['stateful order placement as txn event', defaultStatefulOrderReplacementEvent, false, 0],
Copy link
Contributor

Choose a reason for hiding this comment

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

stateful orders can be both txn & block events?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I copied this part from stateful-order-place-handler.test.ts, i can remove one if you think not needed to test it. i don't have full context

RETURNING * INTO order_record;

IF NOT FOUND THEN
RAISE NOTICE 'Unable to cancel replaced order because not found with orderId: %', dydx_uuid_from_order_id(order_id);
Copy link
Contributor

Choose a reason for hiding this comment

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

what's the diff between notice and exception?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

raise notice doesn't abort the transaction. I basically just want to continue here if not found, do you know of a better way to do that?

Copy link
Contributor

Choose a reason for hiding this comment

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

can we surface this logging/add metrics somewhere since we don't expect this to happen?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done!

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7f9416c and f2f6a26.

Files selected for processing (4)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-placement-handler.test.ts (1 hunks)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-replacement-handler.test.ts (1 hunks)
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (4 hunks)
Files skipped from review as they are similar to previous changes (4)
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-placement-handler.test.ts
  • indexer/services/ender/tests/handlers/stateful-order/stateful-order-replacement-handler.test.ts
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql

const oldOrderId = this.event.orderReplacement!.oldOrderId!;
const order = this.event.orderReplacement!.order!;
if (resultRow.errors != null) {
logger.error({
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: the next time an error is added to that postgres script, this can break. Add a check indicating this error is actually an order replacement related error

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added a comment and the test should catch if the error at index 0 is no longer the expected error

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated to check if error message is related to order replacement!

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f2f6a26 and 592b164.

Files selected for processing (2)
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts (1 hunks)
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • indexer/services/ender/src/handlers/stateful-order/stateful-order-replacement-handler.ts
  • indexer/services/ender/src/scripts/handlers/dydx_stateful_order_handler.sql

@chenyaoy chenyaoy merged commit 2446abf into main Jun 12, 2024
11 checks passed
@chenyaoy chenyaoy deleted the chenyao/ender-handle-stateful-order-replacement branch June 12, 2024 19:26
chenyaoy added a commit that referenced this pull request Jul 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants