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

Update updated_at only when there are operations in changes #935

Merged
merged 2 commits into from
Jul 22, 2024

Conversation

window9u
Copy link
Contributor

@window9u window9u commented Jul 21, 2024

What this PR does / why we need it:

The current implementation updates the 'updated_at' field of a document even if the content itself remains unchanged. This happens because changes reported by the client may contain both "presence" and "operations." With the changes introduced in this commit, the 'updated_at' timestamp will only be updated when there is more than one operation in the change list.

Initially, I attempted to address this issue by avoiding database operations when the changes were limited to presence updates. However, this approach was unsuccessful for the following reasons:

  • Changes that include only presence still carry a ClientSeq. If these are not recorded, it can lead to inconsistencies between the client and the server states.

Consequently, it is necessary to store all changes in the database, even if they do not modify the core content, to maintain consistency.

In the context of applications like a whiteboard, where numerous operations can occur simply from moving a mouse pointer, this issue becomes more pronounced. Such frequent minor updates lead to a high volume of changes that primarily involve presence, inflating the ClientSeq and triggering server snapshots, which add to the server's load.

Proposed Solution

Initially, I considered separating presence data from document updates and managing it through an in-memory database like Redis. This would involve removing presence data from the push-pull synchronization mechanism and introducing a new API dedicated to presence management. However, this approach would require extensive modifications to the existing codebase and protocols, affecting not just the current system but other SDKs as well.

Given the complexities involved, I recommend keeping the current push-pull mechanism unchanged for stability and introducing a new API dedicated to broadcasting user presence. This strategy is ideal for applications where excessive updates are driven primarily by presence changes. Developers can shift presence management from the standard update method to this new broadcast API.

This broadcast API is specifically designed to manage presence updates independently. It broadcasts changes to all document subscribers efficiently without modifying the sequence number (ClientSeq) or permanently storing the updates. This design ensures optimal performance by minimizing unnecessary data load and sequence adjustments, making it highly suitable for managing frequent, low-impact changes.

Which issue(s) this PR fixes:

Fixes #916

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


Additional documentation:


Checklist:

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

Summary by CodeRabbit

  • New Features

    • Enhanced logic for updating the UpdatedAt timestamp, now only updating when there are actual operations present.
  • Tests

    • Added a new test case to verify the behavior of the UpdatedAt timestamp based on document updates and operations.
  • Bug Fixes

    • Corrected the conditions under which the UpdatedAt field is updated, ensuring more accurate timestamp management.

@CLAassistant
Copy link

CLAassistant commented Jul 21, 2024

CLA assistant check
All committers have signed the CLA.

Copy link

coderabbitai bot commented Jul 21, 2024

Walkthrough

The changes introduce enhanced logic for updating the UpdatedAt timestamp in the database's document handling. Specifically, the UpdatedAt field is now only updated when relevant operations are present, ensuring more accurate tracking of document modifications. This refinement reduces unnecessary updates and aligns the system's behavior with the intended functionality, particularly regarding changes in the document's root content.

Changes

File Change Summary
server/backend/database/memory/database.go Modified CreateChangeInfos to update UpdatedAt only when operations are present in changes.
server/backend/database/mongo/client.go Adjusted CreateChangeInfos to conditionally update updated_at in the updateFields map based on operations.
server/backend/database/testcases/testcases.go Added a test case verifying UpdatedAt behavior when only presence or both presence and operations are changed.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Database

    Client->>Database: Update Document Presence
    Database->>Database: Check Operations
    alt No Operations
        Database-->>Client: UpdatedAt remains unchanged
    else Operations present
        Database-->>Database: Update UpdatedAt to now
        Database-->>Client: UpdatedAt modified
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Update Document updatedAt to only include Document.Root modifications (#916)
Avoid unnecessary updates to Document's updatedAt when no content changes (#916)

Poem

🐰 In the garden where changes bloom,
A timestamp's dance dispels the gloom.
Only when roots find their way,
Updated moments greet the day.
Hooray for logic, bright and clear,
For every change we hold so dear! 🌼


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

@krapie krapie requested review from hackerwins and krapie July 21, 2024 05:27
@krapie krapie added the enhancement 🌟 New feature or request label Jul 21, 2024
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: 2

Outside diff range, codebase verification and nitpick comments (1)
server/backend/database/testcases/testcases.go (1)

923-923: Add a descriptive comment for the test case.

Consider adding a comment to describe the purpose of this test case for better readability.

// This test case verifies that the `UpdatedAt` timestamp is only updated when there are multiple operations in the change list.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a4ce314 and 94c5fbe.

Files selected for processing (3)
  • server/backend/database/memory/database.go (1 hunks)
  • server/backend/database/mongo/client.go (1 hunks)
  • server/backend/database/testcases/testcases.go (1 hunks)
Additional comments not posted (2)
server/backend/database/memory/database.go (1)

903-909: LGTM! But verify the function usage in the codebase.

The code changes are approved. The logic ensures that the UpdatedAt field is updated only when there are actual operations, which aligns with the PR objectives.

However, ensure that all function calls to CreateChangeInfos are consistent with the new logic.

Verification successful

LGTM! The function usage is consistent with the new logic.

The code changes ensure that the UpdatedAt field is updated only when there are actual operations, and this logic is correctly implemented across the codebase.

  • server/packs/packs.go
  • server/backend/database/database.go
  • server/backend/database/memory/database.go
  • server/backend/database/mongo/client.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `CreateChangeInfos` are consistent with the new logic.

# Test: Search for the function usage. Expect: Ensure correct implementation and consistency.
rg --type go -A 5 $'CreateChangeInfos'

Length of output: 8584


Script:

#!/bin/bash
# Description: Gather context around the usage of `CreateChangeInfos` to ensure correct implementation and consistency.

# Search for the function usage in the implementation files to gather more context.
rg --type go -A 10 -B 10 'CreateChangeInfos' server/packs/packs.go
rg --type go -A 10 -B 10 'CreateChangeInfos' server/backend/database/database.go
rg --type go -A 10 -B 10 'CreateChangeInfos' server/backend/database/memory/database.go
rg --type go -A 10 -B 10 'CreateChangeInfos' server/backend/database/mongo/client.go

Length of output: 2389

server/backend/database/mongo/client.go (1)

895-901: LGTM! But verify the function usage in the codebase.

The code changes are approved. The logic ensures that the updated_at field is updated only when there are actual operations, which aligns with the PR objectives.

However, ensure that all function calls to CreateChangeInfos are consistent with the new logic.

Comment on lines +924 to +948
ctx := context.Background()
docKey := helper.TestDocKey(t)

// 01. Create a client and a document then attach the document to the client.
clientInfo, _ := db.ActivateClient(ctx, projectID, t.Name())
docInfo1, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
docRefKey := docInfo1.RefKey()
assert.NoError(t, clientInfo.AttachDocument(docRefKey.DocID, false))
assert.NoError(t, db.UpdateClientInfoAfterPushPull(ctx, clientInfo, docInfo1))

bytesID, _ := clientInfo.ID.Bytes()
actorID, _ := time.ActorIDFromBytes(bytesID)
doc := document.New(key.Key(t.Name()))
doc.SetActor(actorID)

// 02. update document only presence
assert.NoError(t, doc.Update(func(root *json.Object, p *presence.Presence) error {
p.Set("key", "val")
return nil
}))
pack := doc.CreateChangePack()
updatedAt := docInfo1.UpdatedAt
assert.NoError(t, db.CreateChangeInfos(ctx, projectID, docInfo1, 0, pack.Changes, false))
docInfo2, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
assert.Equal(t, updatedAt, docInfo2.UpdatedAt)
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling.

The code lacks error handling for several operations. Ensure to check for errors after each operation to prevent potential issues.

- docInfo1, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
+ docInfo1, err := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
+ assert.NoError(t, err)

- clientInfo.AttachDocument(docRefKey.DocID, false)
+ assert.NoError(t, clientInfo.AttachDocument(docRefKey.DocID, false))

- db.UpdateClientInfoAfterPushPull(ctx, clientInfo, docInfo1)
+ assert.NoError(t, db.UpdateClientInfoAfterPushPull(ctx, clientInfo, docInfo1))

- bytesID, _ := clientInfo.ID.Bytes()
+ bytesID, err := clientInfo.ID.Bytes()
+ assert.NoError(t, err)

- actorID, _ := time.ActorIDFromBytes(bytesID)
+ actorID, err := time.ActorIDFromBytes(bytesID)
+ assert.NoError(t, err)
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
ctx := context.Background()
docKey := helper.TestDocKey(t)
// 01. Create a client and a document then attach the document to the client.
clientInfo, _ := db.ActivateClient(ctx, projectID, t.Name())
docInfo1, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
docRefKey := docInfo1.RefKey()
assert.NoError(t, clientInfo.AttachDocument(docRefKey.DocID, false))
assert.NoError(t, db.UpdateClientInfoAfterPushPull(ctx, clientInfo, docInfo1))
bytesID, _ := clientInfo.ID.Bytes()
actorID, _ := time.ActorIDFromBytes(bytesID)
doc := document.New(key.Key(t.Name()))
doc.SetActor(actorID)
// 02. update document only presence
assert.NoError(t, doc.Update(func(root *json.Object, p *presence.Presence) error {
p.Set("key", "val")
return nil
}))
pack := doc.CreateChangePack()
updatedAt := docInfo1.UpdatedAt
assert.NoError(t, db.CreateChangeInfos(ctx, projectID, docInfo1, 0, pack.Changes, false))
docInfo2, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
assert.Equal(t, updatedAt, docInfo2.UpdatedAt)
ctx := context.Background()
docKey := helper.TestDocKey(t)
// 01. Create a client and a document then attach the document to the client.
clientInfo, _ := db.ActivateClient(ctx, projectID, t.Name())
docInfo1, err := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
assert.NoError(t, err)
docRefKey := docInfo1.RefKey()
assert.NoError(t, clientInfo.AttachDocument(docRefKey.DocID, false))
assert.NoError(t, db.UpdateClientInfoAfterPushPull(ctx, clientInfo, docInfo1))
bytesID, err := clientInfo.ID.Bytes()
assert.NoError(t, err)
actorID, err := time.ActorIDFromBytes(bytesID)
assert.NoError(t, err)
doc := document.New(key.Key(t.Name()))
doc.SetActor(actorID)
// 02. update document only presence
assert.NoError(t, doc.Update(func(root *json.Object, p *presence.Presence) error {
p.Set("key", "val")
return nil
}))
pack := doc.CreateChangePack()
updatedAt := docInfo1.UpdatedAt
assert.NoError(t, db.CreateChangeInfos(ctx, projectID, docInfo1, 0, pack.Changes, false))
docInfo2, _ := db.FindDocInfoByKeyAndOwner(ctx, clientInfo.RefKey(), docKey, true)
assert.Equal(t, updatedAt, docInfo2.UpdatedAt)

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. I'll apply CodeRabbit's comments after merging this PR.

@hackerwins hackerwins merged commit b494fa2 into yorkie-team:main Jul 22, 2024
4 checks passed
@hackerwins hackerwins changed the title Update 'updated_at' only if there are more than one operation in changes Update updated_at only when there are operations in changes Jul 22, 2024
@window9u window9u deleted the fix-updateAt branch July 22, 2024 06:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement 🌟 New feature or request
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

Update Document updatedAt to only include Document.Root modifications
4 participants