Skip to content

Add support for non-async operations to bit Besql (#9811)#9812

Merged
msynk merged 1 commit intobitfoundation:developfrom
yasmoradi:9811
Feb 6, 2025
Merged

Add support for non-async operations to bit Besql (#9811)#9812
msynk merged 1 commit intobitfoundation:developfrom
yasmoradi:9811

Conversation

@yasmoradi
Copy link
Member

@yasmoradi yasmoradi commented Feb 6, 2025

closes #9811

Summary by CodeRabbit

  • New Features
    • The weather demo now displays two distinct forecast entries with updated summary details for a refreshed experience.
  • Refactor
    • Improved backend command processing now handles operations seamlessly without interruption.
    • Removed an outdated error-handling approach to ensure more consistent and reliable performance.

@yasmoradi yasmoradi requested a review from msynk February 6, 2025 19:26
@coderabbitai
Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The changes adjust how non-asynchronous operations are handled in the Bit Besql framework. In the database context interceptor, command execution methods now check for specific keywords and, when detected, invoke an asynchronous throttling routine instead of throwing an exception. The custom BesqlNonAsyncOperationException has been removed. Additionally, the Weather component demo now uses a synchronous method (SyncVersionTest) that adds two forecasts and commits them synchronously with SaveChanges, reflecting support for non-async operations.

Changes

File(s) Change Summary
src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs, src/Besql/Bit.Besql/BesqlNonAsyncOperationException.cs In BesqlDbContextInterceptor, removed exception throwing by adding a command text check that calls ThrottledSync and marked the keywords array as readonly. Removed BesqlNonAsyncOperationException.
src/Besql/Demo/.../Weather.razor Replaced the NonAsyncOperationError method with SyncVersionTest. Modified AddWeatherForecast to add two forecast objects and use SaveChanges synchronously, updating the forecasts count accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Interceptor as BesqlDbContextInterceptor
    participant Throttle as ThrottledSync
    App->>Interceptor: Execute command (e.g., ReaderExecuted)
    Interceptor->>Interceptor: Check if command text has target keywords
    alt Command is targeted
        Interceptor->>Throttle: Invoke ThrottledSync asynchronously
        Throttle-->>Interceptor: Return processed result
    else Command not targeted
        Interceptor-->>App: Return original result
    end
    Interceptor-->>App: Return final result
Loading
sequenceDiagram
    participant User as User
    participant Weather as Weather Component
    participant DB as Database Context
    User->>Weather: Trigger SyncVersionTest
    Weather->>Weather: Add two forecast objects
    Weather->>DB: Call SaveChanges synchronously
    DB-->>Weather: Acknowledge save
    Weather-->>User: Update forecasts count
Loading

Assessment against linked issues

Objective Addressed Explanation
bit Besql must work with non async operations (#9811)

Poem

Hopping through changes with a skip and a bound,
I update the code where new flows are found.
No more errors for my sync little paws,
Two forecasts dance without async flaws.
Coding in burrows, I rejoice with glee—happy hops for all to see! 🐰🎉

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (2)

10-10: Ensure true immutability of keyword list.
Marking the array reference as readonly prevents reassignment, but the array elements can still be modified at runtime. If true immutability is desired, consider using an immutable data structure or returning an unmodifiable view.


17-22: Handle potential unobserved exceptions from the background task.
Currently, the returned Task from ThrottledSync is ignored (fire-and-forget). If exceptions occur during execution, they may go unobserved. Consider a retry mechanism, error logging, or awaiting the task (based on requirements) to ensure failures are properly handled.

src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (1)

25-25: Consider enhancing the sync operation warning.

While the button text includes a warning, consider making it more prominent by:

  1. Adding a tooltip with detailed explanation
  2. Using a different button style/color to indicate caution
-    <button class="btn btn-primary" @onclick="SyncVersionTest">Sync version (Not recommended at all)</button>
+    <button class="btn btn-warning" 
+            @onclick="SyncVersionTest" 
+            title="Warning: Synchronous operations can block the UI thread and degrade user experience. Use async operations whenever possible.">
+        Sync version (Not recommended)
+    </button>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be4abbb and 4657d26.

📒 Files selected for processing (3)
  • src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (3 hunks)
  • src/Besql/Bit.Besql/BesqlNonAsyncOperationException.cs (0 hunks)
  • src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (3 hunks)
💤 Files with no reviewable changes (1)
  • src/Besql/Bit.Besql/BesqlNonAsyncOperationException.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (3)
src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (2)

44-49: Same caution regarding ignoring ThrottledSync’s returned Task.
This is effectively the same concurrency pattern described in lines 17-22.


71-75: Same caution regarding ignoring ThrottledSync’s returned Task.
This is effectively the same concurrency pattern described in lines 17-22.

src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (1)

83-100: ⚠️ Potential issue

Improve sync implementation and reduce code duplication.

Several issues need attention:

  1. Code is duplicated from AddWeatherForecast
  2. Missing error handling
  3. UI could freeze during sync operations
  4. Same issue with long summary string

Consider these improvements:

     private void SyncVersionTest()
     {
-        using var dbContext = DbContextFactory.CreateDbContext();
-        dbContext.WeatherForecasts.Add(new()
-        {
-            Date = new DateTimeOffset(2024, 1, 4, 10, 10, 10, TimeSpan.Zero),
-            Summary = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z...",
-            TemperatureC = Random.Shared.Next(1, 30)
-        });
-        dbContext.WeatherForecasts.Add(new()
-        {
-            Date = new DateTimeOffset(2024, 1, 4, 10, 10, 10, TimeSpan.Zero),
-            Summary = "Test",
-            TemperatureC = Random.Shared.Next(1, 30)
-        });
-        dbContext.SaveChanges();
-        forecastsCount += 2;
+        try 
+        {
+            using var dbContext = DbContextFactory.CreateDbContext();
+            // Extract common forecast creation logic to reduce duplication
+            var forecasts = CreateTestForecasts();
+            dbContext.WeatherForecasts.AddRange(forecasts);
+            dbContext.SaveChanges();
+            forecastsCount += forecasts.Count;
+        }
+        catch (Exception ex)
+        {
+            // Handle errors appropriately
+            Console.Error.WriteLine($"Error in sync operation: {ex.Message}");
+            throw;
+        }
     }
+    
+    // Helper method to reduce duplication
+    private static List<WeatherForecast> CreateTestForecasts()
+    {
+        return new List<WeatherForecast>
+        {
+            new()
+            {
+                Date = DateTimeOffset.Now,
+                Summary = new string('A', 100),
+                TemperatureC = Random.Shared.Next(1, 30)
+            },
+            new()
+            {
+                Date = DateTimeOffset.Now,
+                Summary = "Test",
+                TemperatureC = Random.Shared.Next(1, 30)
+            }
+        };
+    }

Also, verify the impact of sync operations on UI responsiveness:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for other sync operations that might affect UI
ast-grep --pattern 'SaveChanges()' # Look for sync SaveChanges calls
rg 'CreateDbContext\(' # Look for sync context creation

Length of output: 300


Reduce Synchronous Operations and Code Duplication in Weather Forecast Handling

The shell script searches confirm that synchronous operations (e.g., the CreateDbContext call and subsequent SaveChanges) are used in the Weather.razor file. This supports the review comment’s concerns regarding potential UI freezes, code duplication, and the lack of error handling.

Key points:

  • The sync DbContext creation and SaveChanges() in Weather.razor were identified.
  • No additional instances elsewhere were found that could mitigate UI impact.
  • The proposed improvements—using a try/catch block and extracting shared code to a helper method—are appropriate.

@msynk msynk merged commit 29218aa into bitfoundation:develop Feb 6, 2025
3 checks passed
@yasmoradi yasmoradi deleted the 9811 branch February 7, 2025 05:56
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.

bit Besql must work with non async operations as well

2 participants