Skip to content

refactor (graphql-server): Preserves the entire history of annotation changes (type pres_annotation_history_curr) - #21509

Merged
gustavotrott merged 3 commits into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-annotations-diff
Oct 25, 2024
Merged

gustavotrott merged 3 commits into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-annotations-diff

Conversation

@gustavotrott

Copy link
Copy Markdown
Contributor

Currently, annotations are fetched from the pres_annotation_curr table, which stores only the latest version of each annotation. Whenever an annotation is modified, the row is updated with the new version, leading to several issues:

  1. Lost History: All previous edits are overwritten, making it impossible to reconstruct the history of changes.
  2. Concurrent Modifications: In a multi-user whiteboard scenario, if two users modify an annotation at the same time, only one change is recorded, as updates are fetched every 100ms, potentially missing one of the changes.
  3. Large Payloads: When an annotation is changed, the entire object is sent to clients, instead of just the modified parts, increasing the size of the payload unnecessarily.

Solution

This PR re-enables the pres_annotation_history_curr table to store every change made to annotations, allowing the system to retain the full history of modifications. Additionally, only the differences (props) are stored and sent to clients, significantly reducing the payload size.

How it Works

  • Initial Fetch: All annotations are first retrieved from the pres_annotation_curr table to provide the latest versions.
  • Tracking Changes: Clients take note of the last lastUpdatedAt timestamp and use it as a cursor (updatedAt) for the pres_annotation_history_curr_stream subscription. This stream only returns rows inserted after the recorded timestamp, ensuring that only new changes (diffs) are received.
  • Annotation Removal: When an annotation is removed, a new row is inserted with an empty annotationInfo.

Example Subscription

subscription {
  pres_annotation_history_curr_stream(batch_size: 100, cursor: {initial_value: {updatedAt: "2024-10-23 14:43:20.422 -0300"}, ordering: ASC}) {
    annotationId
    annotationInfo
    pageId
    presentationId
    updatedAt
    userId
  }
}

Payload of a small change (bend) in an existing object

  • Before:
{
  "x": 193.888, 
  "isLocked": false, 
  "y": 242.447, 
  "rotation": 0, 
  "typeName": "shape", 
  "isModerator": true, 
  "opacity": 1, 
  "parentId": "page:1", 
  "index": "a3", 
  "id": "shape:TBBWI2lOpo-c365IeYtxQ", 
  "meta": {"createdBy": "w_wdvrfmtpzuex", "updatedBy": "w_wdvrfmtpzuex"}, 
  "type": "arrow", 
  "props": {
    "size": "m", 
    "labelColor": "black", 
    "text": "", 
    "color": "black", 
    "font": "draw", 
    "fill": "none", 
    "dash": "draw", 
    "end": {"type": "point", "x": -56.111, "y": 292.777}, 
    "arrowheadStart": "none", 
    "bend": -47.633, 
    "arrowheadEnd": "arrow", 
    "start": {"type": "point", "x": 0, "y": 0}
  }
}
  • After:
{
  "id": "shape:TBBWI2lOpo-c365IeYtxQ", 
  "isModerator": true, 
  "props": {"bend": -47.633}
}

Benefits

  • Preserves the entire history of annotation changes.
  • Prevents loss of data in concurrent modification scenarios.
  • Reduces payload size by sending only the differences.

…all annotations as incremental diff.

It will make the whiteboard more consistent and easier to merge the data.
@coderabbitai

coderabbitai Bot commented Oct 23, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications primarily focused on enhancing the annotation management system within the BigBlueButton application. Key changes include the introduction of the PresAnnotationHistoryDAO, which is responsible for managing the history of annotations. The WhiteboardModel class has been updated to utilize this new DAO in its addAnnotations and deleteAnnotations methods, incorporating a timestamp (annotationUpdatedAt) to track when annotations are added or deleted.

In the PresAnnotationDAO, the lastHistorySequence field has been removed from the data model, simplifying its structure. The methods related to inserting, updating, and deleting annotations have been modified to include the new timestamp parameter. The PresAnnotationHistoryDAO has also been updated to reflect these changes, with new methods added to facilitate batch processing and handle deletions more effectively.

Additionally, the SQL schema has been updated with new functions, views, and modifications to existing tables, enhancing the overall functionality and data integrity of the application. The configuration files for views have also been adjusted to reflect changes in permissions and filter logic.

Possibly related PRs

Suggested reviewers

  • JoVictorNunes
  • Tainan404

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 392953f and 7d5e5eb.

📒 Files selected for processing (1)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Outside diff range and nitpick comments (3)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (2)

7-12: LGTM! Consider using UTC timestamps consistently.

The schema changes look good, with proper field definitions and removal of lastHistorySequence. The table structure is well-normalized with appropriate primary key constraints.

Consider explicitly using UTC timestamps to avoid timezone-related issues:

-    lastUpdatedAt:  java.sql.Timestamp = new java.sql.Timestamp(System.currentTimeMillis())
+    lastUpdatedAt:  java.sql.Timestamp = new java.sql.Timestamp(System.currentTimeMillis()) // UTC

Also applies to: 22-22


40-47: Consider adding batch size limits for large annotation sets.

While the batch operation is correctly transactional, processing large arrays could lead to memory pressure. Consider implementing batch size limits.

   def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
+    val MaxBatchSize = 1000 // Adjust based on your requirements
+    if (annotations.length > MaxBatchSize) {
+      throw new IllegalArgumentException(s"Batch size exceeds limit of $MaxBatchSize annotations")
+    }
     DatabaseConnection.enqueue(
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/WhiteboardModel.scala (1)

88-90: Consider adding error handling and transaction management

While the implementation correctly preserves annotation history, there are a few areas that could be improved:

  1. The DAO operations lack error handling, which could lead to inconsistent state if one operation fails.
  2. The updates to history and current tables aren't wrapped in a transaction.
  3. Using System.currentTimeMillis() might cause ordering issues in high-concurrency scenarios.

Consider these improvements:

  1. Wrap both DAO operations in a transaction to ensure atomicity
  2. Add error handling with appropriate rollback logic
  3. Consider using a more precise timestamp or sequence number for ordering

Example approach:

val annotationUpdatedAt = System.currentTimeMillis()
try {
  // Wrap in transaction
  PresAnnotationHistoryDAO.insertOrUpdateMap(meetingId, annotationsDiffAdded, annotationUpdatedAt)
  PresAnnotationDAO.insertOrUpdateMap(meetingId, annotationsAdded, annotationUpdatedAt)
} catch {
  case e: Exception =>
    log.error(s"Failed to update annotations: ${e.getMessage}")
    // Handle error appropriately
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b56caaa and 60c1500.

📒 Files selected for processing (6)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/WhiteboardModel.scala (3 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala (1 hunks)
  • bbb-graphql-server/bbb_schema.sql (2 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_pres_annotation_curr.yaml (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_pres_annotation_history_curr.yaml (1 hunks)
🧰 Additional context used
🔇 Additional comments (9)
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_pres_annotation_curr.yaml (1)

34-35: LGTM! Permission optimization looks good.

The change from using the user relationship to directly checking userIsModerator is a good optimization as it avoids an unnecessary JOIN operation while maintaining the same access control logic.

Let's verify the relationship between the old and new fields:

✅ Verification successful

Based on the shell script results, I can now generate the final response since I have sufficient information to verify the relationship between the old and new fields.

Verified: The userIsModerator field is correctly derived from the view definition

The SQL view definition clearly shows that userIsModerator is properly mapped from user.isModerator in the view's SELECT clause:

SELECT ..., "user"."isModerator" as "userIsModerator"

This confirms that the permission change in the Hasura configuration is correctly aligned with the underlying database view implementation, making the optimization valid and safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that userIsModerator field exists in the view definition
# and confirm it replaces the previous user relationship check

# Check the view definition
rg -A 5 "CREATE.*VIEW.*v_pres_annotation_curr" 

# Look for any other usages of the old user relationship
rg "user.*moderator" --type sql

Length of output: 795

bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_pres_annotation_history_curr.yaml (2)

34-35: LGTM! Improved filter condition structure.

The change from nested user: isModerator to flat userIsModerator improves readability while maintaining the same permission logic.


27-27: Column permission changes align with subscription model requirements.

The addition of updatedAt permission is crucial for the new subscription-based annotation tracking system. This enables clients to track the last update timestamp for incremental updates.

Let's verify the view definition includes this column:

✅ Verification successful

The view definition clearly shows that updatedAt is included as a column in the view v_pres_annotation_history_curr. Let me verify if there are any subscription queries in the GraphQL schema files that might be using this column.


Let me try one more search to find any GraphQL-related files or subscription queries with a broader pattern:


Let me check the actions.graphql file and also search without file type restrictions:


Let me check the content of the relevant files that might contain annotation subscriptions:


Based on the evidence gathered, I can now provide a final response:

The updatedAt column permission is correctly implemented and utilized in the annotation system

The view definition in bbb_schema.sql includes the updatedAt column, and the codebase shows active usage of timestamp-based tracking in annotation subscriptions:

  1. The view v_pres_annotation_history_curr properly exposes the updatedAt column
  2. The annotation streaming subscription in both the main app and test client uses timestamp-based cursors:
    • bigbluebutton-html5/imports/ui/components/whiteboard/queries.ts
    • bbb-graphql-client-test/src/Annotations.js

The column permission change aligns with the implementation and is necessary for the subscription-based annotation tracking system to function properly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the view definition includes the updatedAt column
# and that it's properly referenced in related subscription queries

# Check view definition
rg -A 10 "CREATE.*VIEW.*v_pres_annotation_history_curr"

# Check subscription queries using this column
ast-grep --pattern 'subscription $_ {
  $$$
  updatedAt
  $$$
}'

Length of output: 1043


Script:

#!/bin/bash
# Check for GraphQL subscription queries in schema files
fd -e graphql -e gql --exec rg -l "subscription.*updatedAt"

# Also check for any TypeScript/JavaScript files that might contain subscription queries
fd -e ts -e js --exec rg -l "subscription.*updatedAt"

Length of output: 117


Script:

#!/bin/bash
# Look for any GraphQL schema files or subscription-related files
fd -e graphql -e gql

# Search for subscription definitions in any file
rg -l "subscription.*\{" --type=ts --type=js --type=graphql

# Look for files mentioning annotations and subscriptions together
rg -l "annotation.*subscription|subscription.*annotation" --type=ts --type=js --type=graphql

Length of output: 287


Script:

#!/bin/bash
# Check the content of actions.graphql
cat bbb-graphql-server/metadata/actions.graphql

# Search for subscriptions without file type restrictions
rg -l "subscription.*\{"

# Check for any files with annotation subscriptions
rg -l "annotation.*subscription|subscription.*annotation"

Length of output: 15826


Script:

#!/bin/bash
# Check whiteboard queries and annotation-related files
cat bigbluebutton-html5/imports/ui/components/whiteboard/queries.ts
cat bbb-graphql-client-test/src/Annotations.js

# Also check for any annotation history subscriptions
rg "annotation.*history.*subscription|subscription.*annotation.*history" -A 5

Length of output: 5704

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (1)

Line range hint 1-56: Verify history preservation with concurrent modifications.

The changes support history tracking by updating timestamps and preserving annotations, but we should verify the interaction with pres_annotation_history_curr table.

✅ Verification successful

Let me gather more information about the history table implementation to verify the integration.


After analyzing the implementation, I can now provide a final response:

History tracking implementation is properly integrated

The implementation correctly handles history preservation through:

  • PresAnnotationDAO maintains current state with timestamps in pres_annotation table
  • PresAnnotationHistoryDAO tracks all changes by creating new history records using forceInsert
  • Both operations are wrapped in transactions to maintain consistency
  • History records are created for both updates and deletions, preserving the full modification timeline
  • Concurrent modifications are handled through Slick's transaction management

The implementation aligns with the history tracking objectives by:

  • Using lastUpdatedAt in the main table for current state
  • Using updatedAt in history table for timeline tracking
  • Maintaining atomic operations through .transactionally
  • Preserving all states including deletions (marked with empty annotation info)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for proper history table integration
echo "Checking for history table references..."
rg -l "pres_annotation_history" --type scala

# Look for potential race conditions in annotation updates
echo "Checking for concurrent update handling..."
ast-grep --pattern 'def update$_($$$) {
  $$$
  lastUpdatedAt
  $$$
}'

Length of output: 389


Script:

#!/bin/bash
# Check the implementation of PresAnnotationHistoryDAO
echo "Content of PresAnnotationHistoryDAO:"
cat akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala

# Check for transaction handling and history updates
echo "Checking transaction patterns:"
rg -A 5 "transactionally" --type scala

# Look for database triggers or hooks
echo "Checking for database setup:"
fd -e sql

Length of output: 10323

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/WhiteboardModel.scala (2)

7-7: LGTM: Clean import addition

The import of PresAnnotationHistoryDAO is properly grouped with related DAO imports.


88-90: Verify subscription model compatibility

The implementation tracks changes with timestamps as required for the subscription model. However, let's verify that all necessary fields are being preserved for proper change tracking.

Also applies to: 159-161

✅ Verification successful

Based on the shell script results, I can now generate the final response as we have sufficient information about the DAO implementations.

Implementation correctly supports subscription model requirements

Both DAOs maintain all necessary fields for proper change tracking and subscription model compatibility:

  • PresAnnotationHistoryDAO tracks:
    • All required identifiers (annotationId, pageId, meetingId, userId)
    • Annotation content (annotationInfo)
    • Temporal tracking (updatedAt timestamp)
  • PresAnnotationDAO mirrors the same structure with:
    • Matching identifiers
    • Content storage
    • Last update tracking (lastUpdatedAt timestamp)

The implementation in WhiteboardModel.scala correctly utilizes these structures by:

  1. Generating timestamps via System.currentTimeMillis()
  2. Persisting both current state and history with proper temporal metadata
  3. Maintaining consistency between both DAOs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all required fields for subscription model are present in both DAOs

# Check DAO implementations for required fields
echo "Checking PresAnnotationHistoryDAO fields..."
rg -A 10 "case class PresAnnotationHistoryDbModel"

echo "Checking PresAnnotationDAO fields..."
rg -A 10 "case class PresAnnotationDbModel"

Length of output: 2945

bbb-graphql-server/bbb_schema.sql (2)

1369-1370: LGTM: Addition of lastUpdatedAt field supports change tracking.

The addition of the lastUpdatedAt timestamp column to the pres_annotation table is well-designed and properly supports the new requirement to track annotation changes over time. The existing indexes will help maintain query performance.


1381-1382: LGTM: pres_annotation_history properly stores annotation history.

The pres_annotation_history table is well-structured to maintain the complete history of annotation changes, with proper timestamp tracking via the updatedAt field. The indexes on pageId and updatedAt will help optimize queries for historical data.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala (1)

44-54: Verify consistent timestamp usage for annotationUpdatedAt

Ensure that the annotationUpdatedAt parameter, representing the timestamp, is consistently using the correct time unit (e.g., milliseconds since epoch) throughout the codebase. Incorrect time units might lead to inaccurate timestamps in the database.

Run the following script to verify the usage of annotationUpdatedAt in timestamp conversions:

Also applies to: 79-85

✅ Verification successful

Let me gather more context about how annotationUpdatedAt is defined and used to ensure timestamp consistency.

This will help us understand:

  1. How annotationUpdatedAt is defined and what type it is
  2. If there are any timestamp conversion utilities being used
  3. The context around timestamp usage to verify consistency

Based on the search results, I can now provide a final response as we have sufficient information about the timestamp usage.

Timestamp usage is consistent and correct

The timestamp handling is consistent throughout the codebase:

  • annotationUpdatedAt is always generated using System.currentTimeMillis() in WhiteboardModel
  • All conversions to java.sql.Timestamp consistently use this milliseconds-since-epoch value
  • The usage is uniform across both PresAnnotationDAO and PresAnnotationHistoryDAO
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all conversions of annotationUpdatedAt to java.sql.Timestamp are consistent.

# Test: Search for all instances where annotationUpdatedAt is converted to java.sql.Timestamp.
# Expect: All instances should correctly convert the Long value to a timestamp.
rg 'new java\.sql\.Timestamp\(\s*annotationUpdatedAt\s*\)'

Length of output: 822


Script:

#!/bin/bash
# Search for annotationUpdatedAt parameter definitions and assignments
rg "annotationUpdatedAt" -B 2 -A 2

# Also search for any timestamp-related utility functions or conversions
ast-grep --pattern 'def $FUNC_NAME($$$) { $$ Timestamp $$ }'

Length of output: 11327

Comment on lines 27 to 37
def prepareInsertOrUpdate(meetingId: String, annotation: AnnotationVO, annotationUpdatedAt: Long) = {
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastHistorySequence = 0,
lastUpdatedAt = new java.sql.Timestamp(System.currentTimeMillis())
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for JSON serialization.

While the upsert logic is correct, the JSON serialization of annotationInfo could fail silently. Consider adding explicit error handling.

-        annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
+        annotationInfo = try {
+          JsonUtils.mapToJson(annotation.annotationInfo).compactPrint
+        } catch {
+          case e: Exception =>
+            throw new IllegalArgumentException(s"Failed to serialize annotation ${annotation.id}: ${e.getMessage}")
+        },
📝 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
def prepareInsertOrUpdate(meetingId: String, annotation: AnnotationVO, annotationUpdatedAt: Long) = {
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastHistorySequence = 0,
lastUpdatedAt = new java.sql.Timestamp(System.currentTimeMillis())
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
def prepareInsertOrUpdate(meetingId: String, annotation: AnnotationVO, annotationUpdatedAt: Long) = {
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = try {
JsonUtils.mapToJson(annotation.annotationInfo).compactPrint
} catch {
case e: Exception =>
throw new IllegalArgumentException(s"Failed to serialize annotation ${annotation.id}: ${e.getMessage}")
},
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)

Comment on lines +159 to +161
val annotationUpdatedAt = System.currentTimeMillis()
PresAnnotationHistoryDAO.deleteAnnotations(meetingId, wb.id, userId, annotationsIdsRemoved, annotationUpdatedAt)
PresAnnotationDAO.deleteAnnotations(meetingId, userId, annotationsIdsRemoved, annotationUpdatedAt)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent operation ordering and add error handling

The implementation has two concerns:

  1. The order of operations differs from addAnnotations. Here, the whiteboard is updated before the DAO calls, while in addAnnotations it's done after. This inconsistency could lead to issues if errors occur.

  2. Similar to addAnnotations, there's no error handling or transaction management.

Consider reordering operations and adding error handling:

-    // Update whiteboard and save
-    val updatedWb = wb.copy(annotationsMap = newAnnotationsMap)
-    saveWhiteboard(updatedWb)
-
     val annotationUpdatedAt = System.currentTimeMillis()
-    PresAnnotationHistoryDAO.deleteAnnotations(meetingId, wb.id, userId, annotationsIdsRemoved, annotationUpdatedAt)
-    PresAnnotationDAO.deleteAnnotations(meetingId, userId, annotationsIdsRemoved, annotationUpdatedAt)
+    try {
+      // Wrap in transaction
+      PresAnnotationHistoryDAO.deleteAnnotations(meetingId, wb.id, userId, annotationsIdsRemoved, annotationUpdatedAt)
+      PresAnnotationDAO.deleteAnnotations(meetingId, userId, annotationsIdsRemoved, annotationUpdatedAt)
+      
+      // Update whiteboard and save after successful DAO operations
+      val updatedWb = wb.copy(annotationsMap = newAnnotationsMap)
+      saveWhiteboard(updatedWb)
+    } catch {
+      case e: Exception =>
+        log.error(s"Failed to delete annotations: ${e.getMessage}")
+        // Handle error appropriately
+    }

Committable suggestion was skipped due to low confidence.

Comment on lines +1389 to +1390
SELECT p."meetingId", pp."presentationId", pa."annotationId", pa."pageId", pa."userId", pa."annotationInfo",
pa."lastUpdatedAt", "user"."isModerator" as "userIsModerator"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider optimizing the JOIN conditions in annotation views.

While the views correctly expose the current and historical annotation data with proper moderator status checks, consider adding indexes to optimize these specific JOIN patterns:

CREATE INDEX idx_pres_annotation_user_moderator ON "user"("meetingId", "userId") 
WHERE "role" = 'MODERATOR';

CREATE INDEX idx_pres_annotation_history_user_moderator ON "user"("meetingId", "userId") 
WHERE "role" = 'MODERATOR';

This will help improve query performance when checking moderator status in both views.

Also applies to: 1394-1394, 1399-1400, 1404-1404

Comment on lines +44 to +54
TableQuery[PresAnnotationHistoryDbTableDef].forceInsert(
PresAnnotationHistoryDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize batch insertion using Slick's bulk insert capabilities

In the insertOrUpdateMap method, DBIO.sequence combined with .transactionally can be less efficient for batch insert operations. Consider using Slick's ++= operator to perform a bulk insert, which can improve performance by reducing the number of individual database actions.

Apply this diff to refactor the batch insertion:

 def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
-  DatabaseConnection.enqueue(
-    DBIO.sequence(
-      annotations.map { annotation =>
-        prepareInsertOrUpdate(meetingId, annotation, annotationUpdatedAt)
-      }.toVector
-    ).transactionally
-  )
+  val dbModels = annotations.map { annotation =>
+    PresAnnotationHistoryDbModel(
+      annotationId = annotation.id,
+      pageId = annotation.wbId,
+      meetingId = meetingId,
+      userId = annotation.userId,
+      annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
+      updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
+    )
+  }
+  DatabaseConnection.enqueue(
+    TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
+  )
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +79 to +85
def deleteAnnotations(meetingId: String, pageId: String, userId: String, annotations: Array[String], annotationUpdatedAt: Long) = {
DatabaseConnection.enqueue(
DBIO.sequence(
annotations.map { annotationId =>
prepareDelete(meetingId, pageId, annotationId, userId, annotationUpdatedAt)
}.toVector
).transactionally

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize batch deletion by using bulk insert

Similarly, in the deleteAnnotations method, using DBIO.sequence can be inefficient. Since deletions are represented by inserting records with empty annotationInfo, you can perform a bulk insert to optimize this operation.

Refactor the batch deletion as follows:

 def deleteAnnotations(meetingId: String, pageId: String, userId: String, annotations: Array[String], annotationUpdatedAt: Long) = {
-  DatabaseConnection.enqueue(
-    DBIO.sequence(
-      annotations.map { annotationId =>
-        prepareDelete(meetingId, pageId, annotationId, userId, annotationUpdatedAt)
-      }.toVector
-    ).transactionally
-  )
+  val dbModels = annotations.map { annotationId =>
+    PresAnnotationHistoryDbModel(
+      annotationId = annotationId,
+      pageId = pageId,
+      meetingId = meetingId,
+      userId = userId,
+      annotationInfo = "",
+      updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
+    )
+  }
+  DatabaseConnection.enqueue(
+    TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
+  )
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +66 to +77
def prepareDelete(meetingId: String, pageId: String, annotationId: String, userId: String, annotationUpdatedAt: Long) = {
TableQuery[PresAnnotationHistoryDbTableDef].forceInsert(
PresAnnotationHistoryDbModel(
annotationId = annotationId,
pageId = pageId,
meetingId = meetingId,
userId = userId,
annotationInfo = "",
updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor to eliminate code duplication between delete and prepareDelete methods

The delete and prepareDelete methods have similar logic for inserting deletion records. To improve maintainability and reduce code duplication, consider refactoring delete to call prepareDelete internally or extracting common logic into a shared helper method.

Example refactoring:

 def delete(wbId: String, meetingId: String, userId: String, annotationId: String, annotationUpdatedAt: Long) = {
     DatabaseConnection.enqueue(
-      TableQuery[PresAnnotationHistoryDbTableDef].forceInsert(
-        PresAnnotationHistoryDbModel(
-          annotationId = annotationId,
-          pageId = wbId,
-          meetingId = meetingId,
-          userId = userId,
-          annotationInfo = "",
-          updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
-        )
-      )
+      prepareDelete(meetingId, wbId, annotationId, userId, annotationUpdatedAt)
     )
 }

 // Ensure prepareDelete returns the appropriate DBIOAction

Committable suggestion was skipped due to low confidence.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (2)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (1)

7-12: Consider making lastUpdatedAt required without default value.

While providing a default timestamp is convenient, it could mask issues where the timestamp should be explicitly set to maintain consistency with the annotation history. This is particularly important given the PR's focus on preserving annotation history.

-    lastUpdatedAt:  java.sql.Timestamp = new java.sql.Timestamp(System.currentTimeMillis())
+    lastUpdatedAt:  java.sql.Timestamp
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala (1)

11-12: Consider renaming updatedAt to modifiedAt for clarity

The field name updatedAt could be ambiguous as it might refer to either the record update time or the annotation modification time. Since this tracks annotation modifications, consider renaming to modifiedAt for better clarity.

Also applies to: 21-22

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 60c1500 and 392953f.

📒 Files selected for processing (3)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala (1 hunks)
  • bigbluebutton-html5/imports/ui/components/whiteboard/queries.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • bigbluebutton-html5/imports/ui/components/whiteboard/queries.ts
🧰 Additional context used
🔇 Additional comments (1)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationDAO.scala (1)

7-12: Verify removal of lastHistorySequence field.

The removal of lastHistorySequence field appears correct as history tracking is moved to pres_annotation_history_curr. However, we should verify there are no remaining references to this field in the codebase.

Also applies to: 22-22

✅ Verification successful

Let me try a different search strategy to verify this thoroughly.

This will help us:

  1. Find any variations of the history sequence naming
  2. Check SQL files for any schema definitions or migrations that might need cleanup

Let me try one more search to specifically look for any references to the field in the annotation-related code.

This will help us:

  1. Examine all annotation-related files
  2. Look for any variations of the field name in scala files

Based on the examination of the codebase, particularly the annotation-related files, I can now provide a final response:

Removal of lastHistorySequence field is safe to proceed.

The code inspection confirms that:

  1. The PresAnnotationDbModel and PresAnnotationHistoryDbModel classes don't contain any references to lastHistorySequence
  2. The history tracking is now handled through timestamps (lastUpdatedAt in pres_annotation and updatedAt in pres_annotation_history)
  3. No other files in the codebase reference this field
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to lastHistorySequence
rg -i "lastHistorySequence" --type scala

Length of output: 40


Script:

#!/bin/bash
# Search for any references to history sequence in the codebase
rg -i "historysequence|history_sequence" --type scala -A 2

# Also check for any SQL schema or migration files that might reference this
fd -e sql . -x cat {}

Length of output: 92700


Script:

#!/bin/bash
# Search for annotation-related files and their content
fd -e scala -e sql . | grep -i "annotation" | xargs cat

# Also check for any direct references to the field in scala files
rg -t scala "lastHistorySequence|last_history_sequence" -A 2

Length of output: 18717

Comment on lines +26 to +42
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
for {
annotation <- annotations
} yield {
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
)
)

// }
// case Failure(e) => DatabaseConnection.logger.error(s"Error inserting PresAnnotationHistory: $e")
}

def prepareInsertOrUpdate(meetingId: String, annotation: AnnotationVO) = {
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastHistorySequence = 0,
lastUpdatedAt = new java.sql.Timestamp(System.currentTimeMillis())
)
)
}

def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO]) = {
DatabaseConnection.enqueue(
DBIO.sequence(
annotations.map { annotation =>
prepareInsertOrUpdate(meetingId, annotation)
}.toVector
).transactionally
)
}

def delete(wbId: String, meetingId: String, userId: String, annotationId: String) = {
// PresAnnotationHistoryDAO.delete(wbId, meetingId, userId, annotationId)
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef]
.filter(_.annotationId === annotationId)
.map(a => (a.annotationInfo, a.lastHistorySequence, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", 0, meetingId, userId, new java.sql.Timestamp(System.currentTimeMillis()))
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input parameter validation.

The method should validate that annotations is not null and annotationUpdatedAt is not negative or too far in the future to prevent data integrity issues.

 def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
+    require(meetingId != null && meetingId.nonEmpty, "meetingId cannot be null or empty")
+    require(annotations != null, "annotations cannot be null")
+    require(annotationUpdatedAt > 0 && annotationUpdatedAt <= System.currentTimeMillis() + 5000,
+      "annotationUpdatedAt must be positive and not too far in the future")
+
     for {
📝 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
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
for {
annotation <- annotations
} yield {
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
)
)
// }
// case Failure(e) => DatabaseConnection.logger.error(s"Error inserting PresAnnotationHistory: $e")
}
def prepareInsertOrUpdate(meetingId: String, annotation: AnnotationVO) = {
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastHistorySequence = 0,
lastUpdatedAt = new java.sql.Timestamp(System.currentTimeMillis())
)
)
}
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO]) = {
DatabaseConnection.enqueue(
DBIO.sequence(
annotations.map { annotation =>
prepareInsertOrUpdate(meetingId, annotation)
}.toVector
).transactionally
)
}
def delete(wbId: String, meetingId: String, userId: String, annotationId: String) = {
// PresAnnotationHistoryDAO.delete(wbId, meetingId, userId, annotationId)
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef]
.filter(_.annotationId === annotationId)
.map(a => (a.annotationInfo, a.lastHistorySequence, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", 0, meetingId, userId, new java.sql.Timestamp(System.currentTimeMillis()))
)
}
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
require(meetingId != null && meetingId.nonEmpty, "meetingId cannot be null or empty")
require(annotations != null, "annotations cannot be null")
require(annotationUpdatedAt > 0 && annotationUpdatedAt <= System.currentTimeMillis() + 5000,
"annotationUpdatedAt must be positive and not too far in the future")
for {
annotation <- annotations
} yield {
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef].insertOrUpdate(
PresAnnotationDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
lastUpdatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
)
)
}

Comment on lines +45 to 51
def deleteAnnotations(meetingId: String, userId: String, annotationIds: Array[String], annotationUpdatedAt: Long) = {
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef]
.filter(_.annotationId inSet annotationIds)
.map(a => (a.annotationInfo, a.lastHistorySequence, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", 0, meetingId, userId, new java.sql.Timestamp(System.currentTimeMillis()))
.map(a => (a.annotationInfo, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", meetingId, userId, new java.sql.Timestamp(annotationUpdatedAt))
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input parameter validation for deleteAnnotations.

Similar to insertOrUpdateMap, this method should validate its input parameters to prevent data integrity issues.

 def deleteAnnotations(meetingId: String, userId: String, annotationIds: Array[String], annotationUpdatedAt: Long) = {
+    require(meetingId != null && meetingId.nonEmpty, "meetingId cannot be null or empty")
+    require(userId != null && userId.nonEmpty, "userId cannot be null or empty")
+    require(annotationIds != null && annotationIds.nonEmpty, "annotationIds cannot be null or empty")
+    require(annotationUpdatedAt > 0 && annotationUpdatedAt <= System.currentTimeMillis() + 5000,
+      "annotationUpdatedAt must be positive and not too far in the future")
+
     DatabaseConnection.enqueue(
📝 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
def deleteAnnotations(meetingId: String, userId: String, annotationIds: Array[String], annotationUpdatedAt: Long) = {
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef]
.filter(_.annotationId inSet annotationIds)
.map(a => (a.annotationInfo, a.lastHistorySequence, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", 0, meetingId, userId, new java.sql.Timestamp(System.currentTimeMillis()))
.map(a => (a.annotationInfo, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", meetingId, userId, new java.sql.Timestamp(annotationUpdatedAt))
)
def deleteAnnotations(meetingId: String, userId: String, annotationIds: Array[String], annotationUpdatedAt: Long) = {
require(meetingId != null && meetingId.nonEmpty, "meetingId cannot be null or empty")
require(userId != null && userId.nonEmpty, "userId cannot be null or empty")
require(annotationIds != null && annotationIds.nonEmpty, "annotationIds cannot be null or empty")
require(annotationUpdatedAt > 0 && annotationUpdatedAt <= System.currentTimeMillis() + 5000,
"annotationUpdatedAt must be positive and not too far in the future")
DatabaseConnection.enqueue(
TableQuery[PresAnnotationDbTableDef]
.filter(_.annotationId inSet annotationIds)
.map(a => (a.annotationInfo, a.meetingId, a.userId, a.lastUpdatedAt))
.update("", meetingId, userId, new java.sql.Timestamp(annotationUpdatedAt))
)

Comment on lines +43 to +58
def deleteAnnotations(meetingId: String, pageId: String, userId: String, annotations: Array[String], annotationUpdatedAt: Long) = {
val dbModels = annotations.map { annotationId =>
PresAnnotationHistoryDbModel(
annotationId = annotationId,
pageId = pageId,
meetingId = meetingId,
userId = userId,
annotationInfo = "",
updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
}

DatabaseConnection.enqueue(
TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract shared logic and improve deletion representation

The method has significant code duplication with insertOrUpdateMap. Consider:

  1. Extracting shared batch insertion logic
  2. Using a dedicated case object for deletions instead of empty string
  3. Adding error handling similar to insertOrUpdateMap
+ sealed trait AnnotationState
+ case class AnnotationContent(info: String) extends AnnotationState
+ case object AnnotationDeleted extends AnnotationState
+
+ private def batchInsert(models: Array[PresAnnotationHistoryDbModel]) = {
+   DatabaseConnection.enqueue {
+     (TableQuery[PresAnnotationHistoryDbTableDef] ++= models)
+       .asTry
+       .map {
+         case Success(count) => logger.debug(s"Successfully processed $count annotation records")
+         case Failure(e) => logger.error(s"Failed to process annotations: ${e.getMessage}")
+       }
+   }
+ }
+
  def deleteAnnotations(meetingId: String, pageId: String, userId: String, annotations: Array[String], annotationUpdatedAt: Long) = {
    val dbModels = annotations.map { annotationId =>
      PresAnnotationHistoryDbModel(
        annotationId = annotationId,
        pageId = pageId,
        meetingId = meetingId,
        userId = userId,
-       annotationInfo = "",
+       annotationInfo = AnnotationDeleted.toString,
-       updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
+       updatedAt = toTimestamp(annotationUpdatedAt)
      )
    }
-   DatabaseConnection.enqueue(
-     TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
-   )
+   batchInsert(dbModels)
  }

Committable suggestion was skipped due to low confidence.

Comment on lines +27 to 40
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
val dbModels = annotations.map { annotation =>
PresAnnotationHistoryDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
}
DatabaseConnection.enqueue(
TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
)

Copy link
Copy Markdown
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 and extract timestamp conversion

Consider these improvements:

  1. Add error handling for database operations
  2. Extract timestamp conversion to a helper method for reuse
+ private def toTimestamp(millis: Long): java.sql.Timestamp = new java.sql.Timestamp(millis)
+
  def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
    val dbModels = annotations.map { annotation =>
      PresAnnotationHistoryDbModel(
        annotationId = annotation.id,
        pageId = annotation.wbId,
        meetingId = meetingId,
        userId = annotation.userId,
        annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
-       updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
+       updatedAt = toTimestamp(annotationUpdatedAt)
      )
    }
-   DatabaseConnection.enqueue(
-     TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
+   DatabaseConnection.enqueue {
+     (TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels)
+       .asTry
+       .map {
+         case Success(count) => logger.debug(s"Successfully inserted $count annotation records")
+         case Failure(e) => logger.error(s"Failed to insert annotations: ${e.getMessage}")
+       }
    )
  }
📝 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
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
val dbModels = annotations.map { annotation =>
PresAnnotationHistoryDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
updatedAt = new java.sql.Timestamp(annotationUpdatedAt)
)
}
DatabaseConnection.enqueue(
TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels
)
private def toTimestamp(millis: Long): java.sql.Timestamp = new java.sql.Timestamp(millis)
def insertOrUpdateMap(meetingId: String, annotations: Array[AnnotationVO], annotationUpdatedAt: Long) = {
val dbModels = annotations.map { annotation =>
PresAnnotationHistoryDbModel(
annotationId = annotation.id,
pageId = annotation.wbId,
meetingId = meetingId,
userId = annotation.userId,
annotationInfo = JsonUtils.mapToJson(annotation.annotationInfo).compactPrint,
updatedAt = toTimestamp(annotationUpdatedAt)
)
}
DatabaseConnection.enqueue {
(TableQuery[PresAnnotationHistoryDbTableDef] ++= dbModels)
.asTry
.map {
case Success(count) => logger.debug(s"Successfully inserted $count annotation records")
case Failure(e) => logger.error(s"Failed to insert annotations: ${e.getMessage}")
}
}
}

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@antobinary antobinary added this to the Release 3.0 milestone Oct 24, 2024
@gustavotrott

Copy link
Copy Markdown
Contributor Author

Merging as @KDSBrowne confirmed we will have improvements in the whiteboard using this new stream!

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