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

Refactor AsyncStream #704

Merged
merged 3 commits into from
Nov 4, 2024
Merged

Refactor AsyncStream #704

merged 3 commits into from
Nov 4, 2024

Conversation

rygine
Copy link
Collaborator

@rygine rygine commented Nov 4, 2024

Summary

This PR refactors AsyncStream to be more compliant with the async iterator pattern.

  • Replaced stop() with return()
  • Renamed stopCallback property to onReturn
  • Added throw of error passed to stream callback

The return() method of an async iterator will always be called when the iteration is complete. This allows shutting down streams without manually calling stop().

With these changes, for..await const..of loops will properly throw errors passed into the stream callback.

Summary by CodeRabbit

  • New Features

    • Introduced a new method return in the AsyncStream class for improved stream completion handling.
    • Updated stopCallback to onReturn for clearer callback functionality in the AsyncStream class.
    • Added unit tests for AsyncStream and enhanced test coverage for the Conversation class, including member management and message handling.
  • Bug Fixes

    • Improved error handling in the AsyncStream class, allowing errors to propagate to the caller.
  • Tests

    • Added tests for various functionalities in the Conversation class, including message sending and updating conversation properties.
    • Streamlined tests for conversations to align with updated streaming methods.

@rygine rygine requested a review from a team as a code owner November 4, 2024 21:30
Copy link

changeset-bot bot commented Nov 4, 2024

🦋 Changeset detected

Latest commit: 764d6c0

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@xmtp/node-sdk Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

coderabbitai bot commented Nov 4, 2024

Warning

Rate limit exceeded

@rygine has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 21 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

Reviewing files that changed from the base of the PR and between 244932b and 764d6c0.

Walkthrough

The changes in this pull request primarily focus on the AsyncStream class within the Node SDK. Key modifications include the removal of the error property from the ResolveValue type, renaming the stopCallback property to onReturn, and introducing a new return method to manage stream completion. Additionally, the callback method now throws errors instead of handling them internally. Corresponding updates are made in the Conversation and Conversations classes to reflect these changes. New unit tests for both AsyncStream and Conversation classes are also introduced to validate the updated functionalities.

Changes

File Change Summary
sdks/node-sdk/src/AsyncStream.ts - Removed error property from ResolveValue type.
- Renamed stopCallback to onReturn.
- Updated callback method to throw errors instead of handling them.
- Removed stop method.
- Added return(value: T) method.
sdks/node-sdk/src/Conversation.ts - Updated asyncStream.stopCallback to asyncStream.onReturn in the stream method.
sdks/node-sdk/src/Conversations.ts - Renamed stopCallback to onReturn across multiple streaming methods without changing the logic.
sdks/node-sdk/test/AsyncStream.test.ts - Introduced unit tests for AsyncStream validating value handling and error propagation.
sdks/node-sdk/test/Conversation.test.ts - Added tests for updating conversation properties, member management, message handling, and streaming messages.
sdks/node-sdk/test/Conversations.test.ts - Removed AsyncStream import and updated streamGroups and streamDms methods to simplify invocation.

Possibly related PRs

  • Update Node SDK #694: Involves renaming the stopCallback property to onReturn in the AsyncStream class, directly related to updates in the Conversation class.
  • Add 1:1 messaging to Browser SDK #703: Introduces a new method newDm in the Conversations class, aligning with the changes in stream and callback management in the AsyncStream class.

Suggested reviewers

  • nplasterer

🐇 In the streams where we play,
Errors now find their way,
With onReturn, we cheer,
As the callbacks draw near.
Async flows, clear and bright,
Hopping through code, what a delight! 🐇


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

🧹 Outside diff range and nitpick comments (4)
sdks/node-sdk/test/AsyncStream.test.ts (3)

7-28: Enhance test coverage for value handling.

While the basic value streaming is tested, consider these improvements:

  1. Test the new return() method (mentioned in PR objectives) by properly closing the stream
  2. Validate that no additional values are processed after stream completion
  3. Simplify the test using an array of expected values

Consider this approach:

 it("should return values from callbacks", async () => {
   const stream = new AsyncStream<number>();
+  const expected = [1, 2, 3];
   stream.callback(null, 1);
   stream.callback(null, 2);
   stream.callback(null, 3);

-  let count = 0;
+  const received = [];
   for await (const value of stream) {
-    if (count === 0) {
-      expect(value).toBe(1);
-    }
-    if (count === 1) {
-      expect(value).toBe(2);
-    }
-    if (count === 2) {
-      expect(value).toBe(3);
-      break;
-    }
-    count++;
+    received.push(value);
+    if (received.length === expected.length) {
+      await stream.return();
+      break;
+    }
   }
+  expect(received).toEqual(expected);
+  
+  // Verify no more values are processed after return
+  stream.callback(null, 4);
+  for await (const value of stream) {
+    throw new Error(`Unexpected value: ${value}`);
+  }
 });

30-43: Add cleanup validation after error.

The error handling test is good but could be enhanced to verify proper cleanup after the error.

Consider adding:

 it("should catch an error thrown in the for..await loop", async () => {
   const stream = new AsyncStream<number>();
   stream.callback(null, 1);

   try {
     for await (const value of stream) {
       expect(value).toBe(1);
       throw testError;
     }
   } catch (error) {
     expect(error).toBe(testError);
     expect((error as Error).message).toBe("test");
+    
+    // Verify stream is properly closed after error
+    stream.callback(null, 2);
+    for await (const value of stream) {
+      throw new Error(`Unexpected value: ${value}`);
+    }
   }
 });

45-61: Simplify error assertions and add state verification.

The test has redundant error assertions and could be enhanced to verify stream state after error.

Consider this approach:

 it("should catch an error passed to callback", async () => {
-  const runTest = async () => {
-    const stream = new AsyncStream<number>();
-    stream.callback(testError, 1);
-    try {
-      for await (const _value of stream) {
-        // this block should never be reached
-      }
-    } catch (error) {
-      expect(error).toBe(testError);
-      expect((error as Error).message).toBe("test");
-    }
-  };
+  const stream = new AsyncStream<number>();
+  stream.callback(testError, 1);
 
-  await expect(runTest()).rejects.toThrow(testError);
+  let loopExecuted = false;
+  await expect(async () => {
+    for await (const _value of stream) {
+      loopExecuted = true;
+    }
+  }).rejects.toThrow(testError);
+  
+  // Verify loop was never executed
+  expect(loopExecuted).toBe(false);
+  
+  // Verify stream is properly closed after error
+  stream.callback(null, 2);
+  for await (const value of stream) {
+    throw new Error(`Unexpected value: ${value}`);
+  }
 });
sdks/node-sdk/test/Conversations.test.ts (1)

336-341: LGTM! Consider enhancing test coverage

The implementation correctly uses the async iteration pattern. Consider adding these test cases to improve coverage:

  1. Verify that group messages are properly filtered out
  2. Add error handling scenarios to test the new error propagation functionality mentioned in the PR objectives

Example test case:

it("should properly handle errors in DM streams", async () => {
  const stream = client3.conversations.streamDms();
  // Simulate an error condition
  // Verify that the error is properly propagated
  await expect(async () => {
    for await (const convo of stream) {
      // Force an error condition
    }
  }).rejects.toThrow();
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5dd8eb0 and 244932b.

📒 Files selected for processing (6)
  • sdks/node-sdk/src/AsyncStream.ts (3 hunks)
  • sdks/node-sdk/src/Conversation.ts (1 hunks)
  • sdks/node-sdk/src/Conversations.ts (6 hunks)
  • sdks/node-sdk/test/AsyncStream.test.ts (1 hunks)
  • sdks/node-sdk/test/Conversation.test.ts (0 hunks)
  • sdks/node-sdk/test/Conversations.test.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • sdks/node-sdk/test/Conversation.test.ts
✅ Files skipped from review due to trivial changes (1)
  • sdks/node-sdk/src/Conversations.ts
🔇 Additional comments (6)
sdks/node-sdk/test/AsyncStream.test.ts (1)

1-4: LGTM: Clean test setup with appropriate imports.

The test setup follows testing best practices with clear imports and a well-defined test error.

sdks/node-sdk/src/Conversation.ts (1)

122-122: LGTM! Property rename aligns with async iterator pattern.

The change from stopCallback to onReturn correctly implements the AsyncStream refactor, better aligning with standard async iterator patterns where return() is used for cleanup.

sdks/node-sdk/test/Conversations.test.ts (1)

Line range hint 305-314: LGTM! Test correctly implements async iteration pattern

The test properly demonstrates the new streaming pattern using for-await-of loop, which automatically handles stream cleanup through the standard return() method.

sdks/node-sdk/src/AsyncStream.ts (3)

15-15: LGTM!

The addition of the onReturn property is appropriate and aligns with the intended functionality.


29-29: LGTM!

Changing the error handling to throw errors ensures that errors are properly propagated to the caller.


65-72: LGTM!

The addition of the return method correctly implements the async iterator protocol, allowing for proper stream completion.

sdks/node-sdk/test/AsyncStream.test.ts Outdated Show resolved Hide resolved
Copy link

cloudflare-workers-and-pages bot commented Nov 4, 2024

Deploying xmtp-js-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 764d6c0
Status: ✅  Deploy successful!
Preview URL: https://a513f7ac.xmtp-js.pages.dev
Branch Preview URL: https://rygine-fix-async-stream.xmtp-js.pages.dev

View logs

@rygine rygine requested a review from a team as a code owner November 4, 2024 21:46
@rygine rygine merged commit ea74562 into main Nov 4, 2024
12 checks passed
@rygine rygine deleted the rygine/fix-async-stream branch November 4, 2024 22:20
@coderabbitai coderabbitai bot mentioned this pull request Nov 6, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 19, 2024
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