Skip to content

Improve bit besql (#9799)#9800

Merged
msynk merged 3 commits intobitfoundation:developfrom
yasmoradi:9799
Feb 5, 2025
Merged

Improve bit besql (#9799)#9800
msynk merged 3 commits intobitfoundation:developfrom
yasmoradi:9799

Conversation

@yasmoradi
Copy link
Member

@yasmoradi yasmoradi commented Feb 5, 2025

closes #9799

Summary by CodeRabbit

  • New Features
    • Added interactive controls on the weather page to pause and resume file synchronization.
    • Introduced an error demonstration trigger that alerts users when unsupported synchronous operations are attempted.
    • Enhanced weather forecast displays with enriched summary details for improved clarity.

@yasmoradi yasmoradi requested a review from msynk February 5, 2025 18:16
@coderabbitai
Copy link

coderabbitai bot commented Feb 5, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The update introduces new error handling for synchronous operations by adding methods that throw exceptions in a database context interceptor and providing a dedicated exception class. In addition, pause/resume synchronization functionality has been implemented across storage classes and an interface, with a new list to track paused files and methods to control persistence operations. The Weather component has been updated with extra buttons and methods to invoke the new pause/resume and error-triggering functionalities while modifying forecast data.

Changes

File(s) Change Summary
src/.../BesqlDbContextInterceptor.cs Added three methods (ReaderExecuted, NonQueryExecuted, ScalarExecuted) that throw a non-async exception; modified IsTargetedCommand to use a class-level keywords array; changed filesSyncIds initialization to a ConcurrentDictionary.
src/.../BesqlNonAsyncOperationException.cs Introduced a new exception class BesqlNonAsyncOperationException (inherits from ApplicationException) to signal unsupported synchronous operations.
src/.../BrowserCacheBesqlStorage.cs, src/.../IBesqlStorage.cs, src/.../NoopBesqlStorage.cs Added a nullable pausedFilesList to track paused files; implemented new PauseSync and ResumeSync methods in storage classes and updated the interface to include these methods.
src/.../Weather.razor Added two new buttons triggering PauseResumeSync and NonAsyncOperationError methods; updated AddWeatherForecast to modify the forecast object's structure; implemented methods to pause synchronization, add forecasts with delays, and resume synchronization, as well as to simulate non-async operation errors.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Application
    participant Interceptor as DbContextInterceptor
    Client->>Interceptor: Call sync method (ReaderExecuted/NonQueryExecuted/ScalarExecuted)
    Interceptor-->>Client: Throw BesqlNonAsyncOperationException
Loading
sequenceDiagram
    participant User as End User
    participant UI as Weather Component
    participant Storage as BesqlStorage Service
    
    User->>UI: Click "Pause / resume sync" button
    UI->>Storage: Invoke PauseSync()
    UI->>UI: Call AddWeatherForecast (with delay)
    UI->>Storage: Invoke ResumeSync()
    Storage-->>UI: Acknowledge resumed sync
Loading

Poem

I'm a bouncy rabbit, in code I delight,
Hopping through changes from morning to night.
Errors now thrown when sync dares to be,
And paused files resume with swift esprit.
With UI buttons and methods so keen,
I wiggle my nose at this code garden scene! 🐇


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 (9)
src/Besql/Bit.Besql/BesqlNonAsyncOperationException.cs (1)

3-5: Consider inheriting from Exception instead of ApplicationException.

Microsoft recommends against using ApplicationException as a base class. It was originally intended as a way to distinguish between developer-created exceptions and runtime exceptions, but this pattern was not widely adopted and is now considered unnecessary.

-public class BesqlNonAsyncOperationException() : ApplicationException("Bit Besql only support async operations.")
+public class BesqlNonAsyncOperationException() : Exception("Bit Besql only support async operations.")
src/Besql/Bit.Besql/IBesqlStorage.cs (2)

9-11: Consider renaming methods for clarity and consistency.

The "Sync" suffix typically indicates a synchronous operation, but ResumeSync is asynchronous. Consider renaming to better reflect the operation type:

-void PauseSync();
+void PausePersistence();

-Task ResumeSync();
+Task ResumePersistenceAsync();

9-11: Add XML documentation for new methods.

Please add XML documentation to describe the purpose and behavior of these methods.

+/// <summary>
+/// Pauses the persistence operations. All subsequent persist operations will be queued.
+/// </summary>
 void PauseSync();

+/// <summary>
+/// Resumes persistence operations and processes any queued operations.
+/// </summary>
+/// <returns>A task that represents the asynchronous operation.</returns>
 Task ResumeSync();
src/Besql/Bit.Besql/NoopBesqlStorage.cs (1)

15-22: Add XML documentation for new methods.

Please add XML documentation to maintain consistency with interface documentation.

+/// <inheritdoc />
 public void PauseSync()
 {
 }

+/// <inheritdoc />
 public Task ResumeSync()
 {
     return Task.CompletedTask;
 }
src/Besql/Bit.Besql/BrowserCacheBesqlStorage.cs (2)

7-7: Make field readonly.

The pausedFilesList field is only set in PauseSync and cleared in ResumeSync. Consider making it readonly to prevent accidental modifications.

-HashSet<string>? pausedFilesList;
+private readonly HashSet<string>? pausedFilesList;

25-42: Add XML documentation for new methods.

Please add XML documentation to maintain consistency with interface documentation.

+/// <inheritdoc />
 public void PauseSync()
 {
     pausedFilesList = [];
 }

+/// <inheritdoc />
 public async Task ResumeSync()
 {
     if (pausedFilesList is null)
         throw new InvalidOperationException("Besql storage is not paused.");
src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (1)

10-10: LGTM! Consider making the keywords array readonly.

The keywords array has been correctly moved to class level for better reusability.

-    private string[] keywords = ["INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP"];
+    private readonly string[] keywords = ["INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP"];
src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (2)

38-48: Consider extracting the large string literal to a constant.

The large string literal in the weather forecast summary makes the code harder to read and maintain.

+    private const string LongSummary = "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..." // truncated for brevity
     private async Task AddWeatherForecast()
     {
         await using var dbContext = await DbContextFactory.CreateDbContextAsync();
         await dbContext.WeatherForecasts.AddAsync(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...",
+                Summary = LongSummary,
                 TemperatureC = Random.Shared.Next(1, 30)
             });

83-87: Consider adding a warning comment about sync operation.

The method demonstrates a sync operation error, but it would be helpful to add a comment explaining why this is problematic.

     private void NonAsyncOperationError()
     {
+        // This method demonstrates why sync operations are not supported in Blazor WebAssembly.
+        // It will throw BesqlNonAsyncOperationException as sync operations can block the UI thread.
         using var dbContext = DbContextFactory.CreateDbContext();
         forecastsCount = dbContext.WeatherForecasts.Count(); // This wouldn't work in blazor wasm / besql.
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fbe0e3f and 1b71ddb.

📒 Files selected for processing (6)
  • src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (3 hunks)
  • src/Besql/Bit.Besql/BesqlNonAsyncOperationException.cs (1 hunks)
  • src/Besql/Bit.Besql/BrowserCacheBesqlStorage.cs (1 hunks)
  • src/Besql/Bit.Besql/IBesqlStorage.cs (1 hunks)
  • src/Besql/Bit.Besql/NoopBesqlStorage.cs (1 hunks)
  • src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (4)
src/Besql/Bit.Besql/BrowserCacheBesqlStorage.cs (1)

27-27: Verify C# version compatibility.

The collection expression syntax [] requires C# 12. Ensure your project targets a compatible version or use the traditional syntax.

-pausedFilesList = [];
+pausedFilesList = new HashSet<string>();
src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs (1)

12-18: LGTM! Consistent error handling for synchronous operations.

The implementation correctly enforces async-only operations by throwing BesqlNonAsyncOperationException for all synchronous methods.

Let's verify that all sync methods are properly intercepted:

Also applies to: 34-40, 56-62

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check for any sync method calls that might bypass the interceptor

# Search for direct sync method calls in the codebase
rg -A 5 '\.(Reader|NonQuery|Scalar)Executed\(' --type cs

Length of output: 58


We need additional verification to confirm that all synchronous methods (ReaderExecuted, NonQueryExecuted, and ScalarExecuted) correctly throw the exception. Let's run a script to display the relevant parts of the implementation in the file. This script will check each method definition for the expected exception throw.


🏁 Script executed:

#!/bin/bash
# Verify that all synchronous execution methods in BesqlDbContextInterceptor throw BesqlNonAsyncOperationException.

echo "Checking for ReaderExecuted method:"
rg -n "public DbDataReader ReaderExecuted.*throw new BesqlNonAsyncOperationException" --type cs src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

echo "Checking for NonQueryExecuted method:"
rg -n "public int NonQueryExecuted.*throw new BesqlNonAsyncOperationException" --type cs src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

echo "Checking for ScalarExecuted method:"
rg -n "public object ScalarExecuted.*throw new BesqlNonAsyncOperationException" --type cs src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

Length of output: 674


🏁 Script executed:

#!/bin/bash
# Verify that each synchronous method in BesqlDbContextInterceptor correctly throws BesqlNonAsyncOperationException.

echo "Searching for BesqlNonAsyncOperationException usage in the file:"
rg -n "BesqlNonAsyncOperationException" src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

echo -e "\nDisplaying ReaderExecuted segment (lines 12-18):"
sed -n '12,18p' src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

echo -e "\nDisplaying NonQueryExecuted segment (lines 34-40):"
sed -n '34,40p' src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

echo -e "\nDisplaying ScalarExecuted segment (lines 56-62):"
sed -n '56,62p' src/Besql/Bit.Besql/BesqlDbContextInterceptor.cs

Length of output: 1522


Synchronous methods correctly enforce async-only operations.

  • The ReaderExecuted method (lines 12–18) throws BesqlNonAsyncOperationException.
  • The NonQueryExecuted method (lines 34–40) throws BesqlNonAsyncOperationException.
  • The ScalarExecuted method (lines 56–62) throws BesqlNonAsyncOperationException.
src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (2)

24-25: LGTM! Clear button labels for testing functionality.

The buttons are appropriately labeled to indicate their purpose.


65-81: LGTM! Proper error handling in pause/resume sync.

The implementation correctly uses try-finally to ensure sync is always resumed, even if an error occurs.

@msynk msynk merged commit b3b61f1 into bitfoundation:develop Feb 5, 2025
2 checks passed
@yasmoradi yasmoradi deleted the 9799 branch February 6, 2025 12:46
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 needs improvements

2 participants