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 tests for event batch publisher implementation #924

Merged
merged 2 commits into from
Nov 4, 2024
Merged

Conversation

chacha912
Copy link
Contributor

@chacha912 chacha912 commented Nov 4, 2024

What this PR does / why we need it?

Fix tests that were broken after introducing the event batch publisher

Before After
image image
- Events were published immediately
- Only current subscribers received events
- Events are batched before publishing
- Events are delivered based on subscription status at batch publish time

1. Fix watched event delivery to late subscribers

With batched delivery, watched events could be sent to clients who subscribed after the initial watch event occurred.

  • As shown in the second image, client B receives client A's watched event later.
  • Fixed this by preventing watched event publish to clients who already know about the watch state.

2. Update attach event test sequencing

The change in event delivery timing affected how attach and subscribe events work:

  • Previously: changed event was immediate, so late subscriptions missed the synced event
  • Now: events are batched, so even late subscriptions can receive the events
  • Modified test order of attach/subscribe sequence to ensure deterministic behavior

Any background context you want to provide?

What are the relevant tickets?

Fixes #
Related yorkie-team/yorkie#1052

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Improved handling of client presence during event processing to prevent duplicate entries.
    • Enhanced synchronization logic for presence updates across clients.
  • Bug Fixes

    • Fixed issues in integration tests for synchronization modes and error handling, ensuring reliable behavior under various conditions.
  • Tests

    • Added comprehensive assertions to presence management tests for better validation of expected behavior.

Copy link

coderabbitai bot commented Nov 4, 2024

Walkthrough

The pull request introduces modifications to the applyWatchStream method in the Document class, adding a conditional check to prevent duplicate processing of "watched" events for clients already present in the onlineClients set. Additionally, it updates integration tests for the Yorkie client to ensure proper handling of synchronization modes and error scenarios, including the addition of await for asynchronous operations. The presence management tests are also enhanced with new assertions to verify initial presence states and synchronization of presence updates across clients.

Changes

File Path Change Summary
packages/sdk/src/document/document.ts Modified applyWatchStream to add a check for existing clients in onlineClients to prevent duplicates. Minor formatting adjustments and comments added.
packages/sdk/test/integration/client_test.ts Updated integration tests to include await for changeSyncMode calls and refined error handling logic. Added checks for remote change events in various sync modes.
packages/sdk/test/integration/presence_test.ts Enhanced presence management tests with assertions for initial presence states and synchronization of presence updates across clients. Added checks for presence updates during sync mode changes.

Possibly related PRs

  • Introduce broadcast API for event sharing #884: This PR introduces changes to the applyWatchStream method in the Document class, which is directly related to the modifications made in the main PR regarding client presence handling during watch stream events.

Poem

🐇 In the land of code where rabbits play,
Changes hop in a bright new way.
Watch streams now check, no duplicates found,
Presence updates dance all around.
Tests now await, with clarity bright,
Synchronizing joy, oh what a sight! 🌟


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

🧹 Outside diff range and nitpick comments (4)
packages/sdk/test/integration/presence_test.ts (3)

129-132: Consider improving type safety of presence assertions.

The assertions correctly verify the initial presence states. However, we can improve type safety by creating a type for the presence array structure.

type PresenceEntry = {
  clientID: string;
  presence: { name: string };
};

assert.deepEqual(
  deepSort<PresenceEntry>(doc1.getPresences()),
  deepSort<PresenceEntry>([
    { clientID: c1ID, presence: { name: 'a' } }
  ])
);

Also applies to: 139-145


Line range hint 471-477: Consider making the test more deterministic.

The comment indicates a timing dependency between realtime sync and watch stream resolution. While the current workaround (performing changeSyncMode after sync) works, it might make the test fragile.

Consider these improvements:

  1. Extract the timing-dependent logic into a helper function that ensures deterministic behavior
  2. Add retry logic with timeout for event verification
async function ensureSyncAndModeChange(client: Client, doc: Document) {
  await client.sync();
  await new Promise(resolve => setTimeout(resolve, 100)); // Add small delay
  await client.changeSyncMode(doc, SyncMode.Realtime);
  
  // Add retry logic for event verification
  const maxRetries = 3;
  for (let i = 0; i < maxRetries; i++) {
    try {
      await events.waitAndVerifyNthEvent(/* ... */);
      break;
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
}
🧰 Tools
🪛 Biome

[error] 134-134: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


Line range hint 590-677: Consider adding edge cases to undo/redo tests.

The tests cover basic undo/redo functionality well. Consider adding these edge cases:

  1. Maximum undo stack size behavior
  2. Concurrent presence updates from multiple clients
  3. Undo/redo behavior during network disconnection

Example test case:

it('Should handle undo stack size limits correctly', async function ({ task }) {
  type Presence = { color: string };
  const doc = new yorkie.Document<{}, Presence>(docKey);
  await client.attach(doc, { initialPresence: { color: 'red' } });

  // Fill undo stack to limit
  for (let i = 0; i < 100; i++) {
    doc.update((root, presence) => {
      presence.set({ color: `color${i}` }, { addToHistory: true });
    });
  }

  // Verify oldest entries are removed
  assert.isBelow(doc.getUndoStackForTest().length, 100);
});
🧰 Tools
🪛 Biome

[error] 134-134: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

packages/sdk/test/integration/client_test.ts (1)

758-761: Consider adding error handling for document attachment

While the test verifies basic attachment functionality, it would be good to add explicit error handling for attachment failures.

-    await c1.attach(d1);
-    await c2.attach(d2);
-    await eventCollectorD1.waitAndVerifyNthEvent(1, DocumentSyncStatus.Synced);
+    try {
+      await c1.attach(d1);
+      await c2.attach(d2);
+      await eventCollectorD1.waitAndVerifyNthEvent(1, DocumentSyncStatus.Synced);
+    } catch (err) {
+      assert.fail(`Document attachment failed: ${err.message}`);
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ea5b6f3 and b37f3a4.

📒 Files selected for processing (3)
  • packages/sdk/src/document/document.ts (1 hunks)
  • packages/sdk/test/integration/client_test.ts (10 hunks)
  • packages/sdk/test/integration/presence_test.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/sdk/test/integration/presence_test.ts

[error] 134-134: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (8)
packages/sdk/test/integration/presence_test.ts (1)

134-134: 🛠️ Refactor suggestion

Replace empty object type with explicit interface.

The static analysis tool correctly flags the use of {} as a type. This can lead to type safety issues.

-deepSort([{ clientID: InitialActorID, presence: {} }])
+interface EmptyPresence {}
+deepSort([{ clientID: InitialActorID, presence: {} as EmptyPresence }])

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome

[error] 134-134: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

packages/sdk/test/integration/client_test.ts (6)

379-380: LGTM: Proper handling of sync mode changes

The addition of await for changeSyncMode calls ensures proper synchronization when switching between different sync modes.


400-401: LGTM: Consistent async handling

Consistent use of await for sync mode changes maintains proper test sequencing.


422-423: LGTM: Proper restoration of realtime sync

The test correctly verifies that switching back to realtime sync mode properly restores bidirectional synchronization.


772-772: LGTM: Push-only mode sync optimization

The test correctly verifies that unnecessary syncs are avoided in push-only mode and proper sync occurs when switching back to realtime mode.

Also applies to: 783-783


624-624: LGTM: Push-only mode verification

The test properly verifies that remote changes are prevented in push-only mode and restored when switching back to realtime mode.

Also applies to: 638-638

✅ Verification successful

Based on the search results, I can now verify the review comment. The codebase shows consistent handling of push-only mode across test files and implementation. Specifically:

  1. The test in client_test.ts properly verifies push-only mode behavior by:

    • Testing the transition to push-only mode
    • Verifying that remote changes are prevented
    • Checking restoration of sync when switching back to realtime mode
  2. The implementation in attachment.ts correctly handles push-only mode by:

    • Only allowing local changes to be pushed (hasLocalChanges() check)
    • Preventing remote changes from being processed
  3. The client implementation in client.ts properly manages the mode transitions and sync behavior.

LGTM: Push-only mode implementation is verified

The test correctly validates the push-only mode behavior, and the implementation consistently handles this mode across the codebase. The synchronization restrictions are properly enforced in both the client and attachment layers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent handling of push-only mode across the codebase
ast-grep --pattern 'changeSyncMode($_, SyncMode.RealtimePushOnly)'

Length of output: 68


Script:

#!/bin/bash
# Let's try a broader search for changeSyncMode usage and SyncMode enum
rg "changeSyncMode" -A 2
rg "SyncMode\." -A 2

Length of output: 39306


707-707: LGTM: Sync-off mode verification

The test properly verifies that remote changes are prevented in sync-off mode and restored when switching back to realtime mode.

Also applies to: 721-721

✅ Verification successful

Based on the code analysis, I can now provide a final response:

Verified: Sync-off mode properly prevents remote changes

The test verifies that:

  • When in RealtimeSyncOff mode, the client does not receive remote changes
  • Remote changes are properly received after switching back to Realtime mode
  • The implementation correctly handles sync mode transitions

The test Should prevent remote changes in sync-off mode specifically validates this behavior by:

  1. Setting up two clients with realtime sync
  2. Changing one client to sync-off mode
  3. Verifying no remote changes are received while in sync-off mode
  4. Confirming changes are received after switching back to realtime mode
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent handling of sync-off mode across the codebase
ast-grep --pattern 'changeSyncMode($_, SyncMode.RealtimeSyncOff)'

Length of output: 67


Script:

#!/bin/bash
# Let's try a broader search for sync mode related code
rg "SyncMode\." -A 2 -B 2

# Also search for changeSyncMode method
rg "changeSyncMode" -A 2 -B 2

# And look for the test file content to understand the test context
cat packages/sdk/test/integration/client_test.ts

Length of output: 97432

packages/sdk/src/document/document.ts (1)

1603-1606: LGTM! Well-structured condition for preventing duplicate event processing.

The added condition effectively prevents duplicate processing of watched events by checking if the client is already tracked and has presence data. This change aligns well with the PR's objective of fixing the event batch publisher implementation and ensures proper event delivery sequencing.

Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins merged commit 9a6ab62 into main Nov 4, 2024
2 checks passed
@hackerwins hackerwins deleted the fix-event-batch branch November 4, 2024 07:33
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