Repository navigation
refactor (graphql-server): Preserves the entire history of annotation changes (type pres_annotation_history_curr) - #21509
Conversation
…all annotations as incremental diff. It will make the whiteboard more consistent and easier to merge the data.
WalkthroughThe pull request introduces several modifications primarily focused on enhancing the annotation management system within the BigBlueButton application. Key changes include the introduction of the In the 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
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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()) // UTCAlso 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 managementWhile the implementation correctly preserves annotation history, there are a few areas that could be improved:
- The DAO operations lack error handling, which could lead to inconsistent state if one operation fails.
- The updates to history and current tables aren't wrapped in a transaction.
- Using
System.currentTimeMillis()might cause ordering issues in high-concurrency scenarios.Consider these improvements:
- Wrap both DAO operations in a transaction to ensure atomicity
- Add error handling with appropriate rollback logic
- 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
📒 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
userrelationship to directly checkinguserIsModeratoris 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
userIsModeratorfield is correctly derived from the view definitionThe SQL view definition clearly shows that
userIsModeratoris properly mapped fromuser.isModeratorin 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 sqlLength 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: isModeratorto flatuserIsModeratorimproves readability while maintaining the same permission logic.
27-27: Column permission changes align with subscription model requirements.The addition of
updatedAtpermission 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
updatedAtis included as a column in the viewv_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
updatedAtcolumn permission is correctly implemented and utilized in the annotation systemThe view definition in
bbb_schema.sqlincludes theupdatedAtcolumn, and the codebase shows active usage of timestamp-based tracking in annotation subscriptions:
- The view
v_pres_annotation_history_currproperly exposes theupdatedAtcolumn- The annotation streaming subscription in both the main app and test client uses timestamp-based cursors:
bigbluebutton-html5/imports/ui/components/whiteboard/queries.tsbbb-graphql-client-test/src/Annotations.jsThe 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=graphqlLength 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 5Length 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_currtable.✅ 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:
PresAnnotationDAOmaintains current state with timestamps inpres_annotationtablePresAnnotationHistoryDAOtracks all changes by creating new history records usingforceInsert- 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
lastUpdatedAtin the main table for current state- Using
updatedAtin 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 sqlLength of output: 10323
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/WhiteboardModel.scala (2)
7-7: LGTM: Clean import additionThe import of
PresAnnotationHistoryDAOis properly grouped with related DAO imports.
88-90: Verify subscription model compatibilityThe 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:
- Generating timestamps via System.currentTimeMillis()
- Persisting both current state and history with proper temporal metadata
- 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 oflastUpdatedAtfield supports change tracking.The addition of the
lastUpdatedAttimestamp column to thepres_annotationtable 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_historyproperly stores annotation history.The
pres_annotation_historytable is well-structured to maintain the complete history of annotation changes, with proper timestamp tracking via theupdatedAtfield. The indexes onpageIdandupdatedAtwill 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 forannotationUpdatedAtEnsure that the
annotationUpdatedAtparameter, 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
annotationUpdatedAtin timestamp conversions:Also applies to: 79-85
✅ Verification successful
Let me gather more context about how
annotationUpdatedAtis defined and used to ensure timestamp consistency.This will help us understand:
- How annotationUpdatedAt is defined and what type it is
- If there are any timestamp conversion utilities being used
- 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:
annotationUpdatedAtis always generated usingSystem.currentTimeMillis()in WhiteboardModel- All conversions to
java.sql.Timestampconsistently 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
| 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) | ||
| ) | ||
| ) |
There was a problem hiding this comment.
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.
| 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) | |
| ) | |
| ) |
| val annotationUpdatedAt = System.currentTimeMillis() | ||
| PresAnnotationHistoryDAO.deleteAnnotations(meetingId, wb.id, userId, annotationsIdsRemoved, annotationUpdatedAt) | ||
| PresAnnotationDAO.deleteAnnotations(meetingId, userId, annotationsIdsRemoved, annotationUpdatedAt) |
There was a problem hiding this comment.
Ensure consistent operation ordering and add error handling
The implementation has two concerns:
-
The order of operations differs from
addAnnotations. Here, the whiteboard is updated before the DAO calls, while inaddAnnotationsit's done after. This inconsistency could lead to issues if errors occur. -
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.
| SELECT p."meetingId", pp."presentationId", pa."annotationId", pa."pageId", pa."userId", pa."annotationInfo", | ||
| pa."lastUpdatedAt", "user"."isModerator" as "userIsModerator" |
There was a problem hiding this comment.
🛠️ 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
| 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) | ||
| ) | ||
| ) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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 |
There was a problem hiding this comment.
🛠️ 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.
| 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) | ||
| ) | ||
| ) | ||
| } |
There was a problem hiding this comment.
🛠️ 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 DBIOActionCommittable suggestion was skipped due to low confidence.
There was a problem hiding this comment.
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.Timestampakka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PresAnnotationHistoryDAO.scala (1)
11-12: Consider renamingupdatedAttomodifiedAtfor clarityThe field name
updatedAtcould be ambiguous as it might refer to either the record update time or the annotation modification time. Since this tracks annotation modifications, consider renaming tomodifiedAtfor better clarity.Also applies to: 21-22
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 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
lastHistorySequencefield appears correct as history tracking is moved topres_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:
- Find any variations of the history sequence naming
- 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:
- Examine all annotation-related files
- 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:
- The
PresAnnotationDbModelandPresAnnotationHistoryDbModelclasses don't contain any references tolastHistorySequence- The history tracking is now handled through timestamps (
lastUpdatedAtinpres_annotationandupdatedAtinpres_annotation_history)- 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 scalaLength 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 2Length of output: 18717
| 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())) | ||
| ) | ||
| } |
There was a problem hiding this comment.
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.
| 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) | |
| ) | |
| ) | |
| ) | |
| } |
| 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)) | ||
| ) |
There was a problem hiding this comment.
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.
| 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)) | |
| ) |
| 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 | ||
| ) | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Extract shared logic and improve deletion representation
The method has significant code duplication with insertOrUpdateMap. Consider:
- Extracting shared batch insertion logic
- Using a dedicated case object for deletions instead of empty string
- 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.
| 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 | ||
| ) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add error handling and extract timestamp conversion
Consider these improvements:
- Add error handling for database operations
- 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.
| 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}") | |
| } | |
| } | |
| } |
|
Automated tests Summary✅ All the CI tests have passed! |
|
Merging as @KDSBrowne confirmed we will have improvements in the whiteboard using this new stream! |



Currently, annotations are fetched from the
pres_annotation_currtable, 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:Solution
This PR re-enables the
pres_annotation_history_currtable 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
pres_annotation_currtable to provide the latest versions.lastUpdatedAttimestamp and use it as a cursor (updatedAt) for thepres_annotation_history_curr_streamsubscription. This stream only returns rows inserted after the recorded timestamp, ensuring that only new changes (diffs) are received.annotationInfo.Example Subscription
Payload of a small change (bend) in an existing object
{ "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} } }{ "id": "shape:TBBWI2lOpo-c365IeYtxQ", "isModerator": true, "props": {"bend": -47.633} }Benefits