Skip to content

add session reconnect #1060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
May 22, 2025
Merged

Conversation

iceljc
Copy link
Collaborator

@iceljc iceljc commented May 19, 2025

No description provided.

@iceljc iceljc requested a review from Oceania2018 May 19, 2025 19:56
@iceljc iceljc changed the title Test/google realtime add session reconnect May 19, 2025
@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Change Summary: The code changes mainly focus on improving modularity and maintainability by refactoring the namespace organization, updating class properties and method implementations, and adding new functionalities related to websocket session management, authorization handling, and extension methods for string utilities. Additionally, it aims to improve performance and scalability by conditionally loading services and enhancing the reconnect logic for real-time hooks.

Identified Issues

Issue 1: Use of Nullable Reference Types

  • Description: In StringExtensions.cs, the updated method signature uses a nullable type for str which aligns with modern C# practices to handle null values more explicitly.
  • Suggestion: Continue using nullable types and the ? symbol where appropriate to prevent potential NullReferenceException.
  • Example:
    // Before
    public static string IfNullOrEmptyAs(this string str, string defaultValue)
    // After
    public static string IfNullOrEmptyAs(this string? str, string defaultValue)

Issue 2: Repeated Logic in Authorization

  • Description: The repetitive user validation logic was present across multiple controllers and has been replaced by a single [BotSharpAuth] attribute.
  • Suggestion: Use the newly created attribute consistently to centralize authorization logic and enhance code maintainability.
  • Example:
    [BotSharpAuth]
    [HttpPost("/refresh-agents")]
    public async Task<string> RefreshAgents()
    {

Issue 3: Conditional Logic for Hosted Services

  • Description: CrontabPlugin.cs now conditionally adds hosted services based on settings.
  • Suggestion: Ensure configuration settings are correctly managed and logged for debugging if issues arise in development or production.
  • Example:
    if (settings.Watcher?.Enabled == true)
    {
        services.AddHostedService<CrontabWatcher>();
    }

Issue 4: Resource Management with Websocket

  • Description: In BotSharpRealtimeSession.cs, resource management practices are improved to prevent operation on disposed objects.
  • Suggestion: Always check disposal status before performing operations that rely on the object's state.
  • Example:
    if (_disposed || _websocket.State != WebSocketState.Open)
    {
        return;
    }

Overall Assessment

The code changes significantly enhance the maintainability and scalability of the BotSharp application. The refactoring and use of attributes for common logic reduce code duplication and potential for errors. There are clear improvements in handling nullable types, conditional service registration, and resource management with websockets, aligning the implementation with best practices for modern C# development. Future improvements can focus on ensuring comprehensive exception handling and thorough unit tests, especially for the new functionalities added.

@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Change Summary: This code change introduces constants for AgentMode, improves property naming consistency, enhances authorization checks, adds new classes for settings and attributes, and improves logic for reconnecting to services. The aim is to improve code clarity, enhance maintainability, and add functionality.

Identified Issues

Issue 1: [Code Clarity and Maintainability]

  • Description: The code uses hardcoded strings for agent modes ("eager" and "lazy"), which can lead to errors if used inconsistently.
  • Suggestion: Use constants or enums to represent these strings consistently.
    // Before modification
    public string Mode { get; set; } = "eager";
    
    // After modification
    public string Mode { get; set; } = AgentMode.Eager;

Issue 2: [Method Naming Consistency]

  • Description: Method names need to consistently represent their function, such as SetAgentType vs SetType.
  • Suggestion: Ensure consistent naming across similar methods to improve readability.
    // Before
    public Agent SetAgentType(string type)
    
    // After
    public Agent SetType(string type)

Issue 3: [Resource Management]

  • Description: In the Dispose methods, checks for _disposed are missing before accessing resources.
  • Suggestion: Add checks to prevent operations on already disposed objects.
    if (_disposed) return;
    _disposed = true;
    _webSocket.Dispose();

Issue 4: [Authorization Logic]

  • Description: Authorization checks could be more elegantly handled using custom authentication attributes.
  • Suggestion: Utilize attributes like BotSharpAuthAttribute for cleaner interface-level authorization.

Overall Evaluation

The code introduces meaningful improvements in terms of structure and readability through the use of constants and improved naming for methods. The addition of settings classes helps in future configurations and adaptability. Proper resource management and further abstractions like custom attributes for security are also added, contributing to cleaner and more robust code.

@@ -0,0 +1,7 @@
namespace BotSharp.Abstraction.Agents.Enums;

public class AgentMode
Copy link
Member

Choose a reason for hiding this comment

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

This should be called RoutingMode

@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Change Overview: The primary goals of the code changes are to improve naming conventions for clarity, introduce new settings for crontab and routing, enhance logging capability, and ensure that certain features are only enabled when necessary.

Identified Issues

Issue 1: Inconsistent Naming Conventions

  • Description: The naming convention for methods and properties should be consistent and descriptive.
  • Suggestion: Adopt a consistent naming strategy, such as using SetRoutingMode uniformly across related code.
  • Example:
    // Before change
    public Agent SetAgentMode(string mode)
    
    // After change
    public Agent SetRoutingMode(string? mode)
    

Issue 2: Nullable Reference Types

  • Description: The Mode property is made nullable without a specific reason provided in the code.
  • Suggestion: Ensure that the nullability of reference types is intentional and document the reasoning for the change to prevent future confusion.
  • Example:
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Mode { get; set; }
    Add comments or documentation to clarify why Mode is nullable.

Issue 3: Potential Missing Check for null

  • Description: In BotSharpRealtimeSession, there should be checks or handling for possible null dereference before using _webSocket.
  • Suggestion: Check for null values before using objects, which helps to avoid runtime exceptions.

Issue 4: Logging Improvements

  • Description: The logging process can be enhanced with more context for better troubleshooting and monitoring.
  • Suggestion: Use more descriptive log messages and include additional data where possible, such as Provider in the logging warnings.

Overall Evaluation

The code presents a good effort in updating and maintaining the infrastructure. However, consistent naming conventions, proper handling for nullable types, and thorough logging are crucial for long-term maintainability and comprehensibility. Future improvements can include adding more robust error handling and ensuring that changes do not introduce any unintended null reference exceptions.

@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Change Overview: The main purpose of these code changes is to enhance the clarity and functionality of the codebase by refactoring code comments, renaming methods and variables, using nullable reference types, adding new configuration settings, and incorporating new routes and session handling functionalities. This change mainly impacts code readability and maintainability and ensures better handling of optional parameters and states.

Issues Identified

Issue 1: Naming Consistency

  • Description: The name "Mode" was changed to "RoutingMode" in multiple locations to better align with the context.
  • Suggestion: This renaming is beneficial for clarity. Ensure all references to "Mode" are updated consistently to prevent any misreferences.
  • Example:
    // Before
    public string Mode { get; set; } = "eager";
    // After
    public string? RoutingMode { get; set; }

Issue 2: Nullable Reference Types

  • Description: The code has been updated to use nullable reference types in places like SetRoutingMode for better null handling.
  • Suggestion: Ensure that null checks are implemented wherever these nullable types are used to avoid potential null reference exceptions.

Issue 3: Configuration Binding

  • Description: New settings such as CrontabSettings are bound from the configuration.
  • Suggestion: Ensure detailed documentation or configuration samples are available for users to properly configure these settings.

Issue 4: Logging Improvements

  • Description: Logging has been enhanced with context-specific details, especially in debug sections.
  • Suggestion: Consider standardizing log formats and levels across the project for better logging consistency.

Issue 5: Potential Unnecessary Return Checks

  • Description: In the BotSharpRealtimeSession and similar classes, there are checks like '_disposed || websocketState != Open' before performing actions.
  • Suggestion: These checks are good, but ensure they are consistently applied across all methods where similar resources are accessed (e.g., SendEventAsync).

General Evaluation

The code changes are generally well-thought-out, making the system more resilient and easier to maintain. The switch to nullable reference types and better logging practices will significantly help in debugging and future development. However, special care should be given to ensure consistency across different areas of the codebase, maintaining clear documentation around newly added features and changes, and optimizing any redundant checks or processes.

var (isAdmin, user) = await userService.IsAdminUser(userIdentity.Id);
if (!isAdmin || user == null)
{
context.Result = new BadRequestResult();
Copy link
Contributor

Choose a reason for hiding this comment

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

Can return Unauthorized().

@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Purpose of the Change: The code changes focus on refactoring and enhancing the maintainability of the BotSharp system. They include renaming variables for clarity, implementing [JsonIgnore] attributes for optional fields, and optimizing the code structure, especially around RoutingMode and session management.

Issues Identified

Issue 1: Naming Clarity

  • Description: In the Agent class and related methods, the term Mode has been replaced with RoutingMode to enhance clarity.
  • Suggestion: This change improves the readability and maintainability of the code by making the purpose of these variables more evident.
  • Example:
    // Before
    public string Mode { get; set; }
    // After
    public string? Mode { get; set; }

Issue 2: Null Handling

  • Description: The use of nullable types along with JsonIgnore attributes. The use of string? and JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull) helps to handle null values more robustly.
  • Suggestion: Continue this practice where applicable, as it reduces potential null reference exceptions and unnecessary serialization.
  • Example:
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Mode { get; set; }

Issue 3: Dependency Injection and Configuration

  • Description: The CrontabSettings have been added to support configurable services depending on the settings.
  • Suggestion: Ensure all services leveraging dependency injection and configuration binding have appropriate null checks or fallbacks.

Issue 4: (Potential Bug) WebSocket Handling

  • Description: In BotSharpRealtimeSession, there's an incomplete check of WebSocket state before sending or closing.
  • Suggestion: Ensure the WebSocket connection is correctly checked and managed to prevent runtime errors.
  • Example:
    if (_disposed || _websocket.State != WebSocketState.Open) return;

Overall Evaluation

The codebase improvements primarily enhance clarity and maintainability through better naming conventions and introducing settings for configurability. It addresses many best practices such as nullable handling and clearer service configuration. However, more thorough testing should be conducted, especially concerning asynchronous processes and WebSocket management, to ensure robustness.

@GGHansome
Copy link

Auto Review Result:

Code Review Summary

Change Overview: The code primarily renames variables and refactors method signatures for better clarity. It also adds new classes and service integration, such as Crontab settings and BotSharp authorization attributes. Additionally, it introduces a feature for determining whether to reconnect a real-time hub connection and conditional service registration in dependency injection.

Identified Issues

Issue 1: Naming Consistency

  • Description: There are name changes from Mode to RoutingMode to make the attribute more descriptive. However, in some areas like the method SetAgentMode, it remains unchanged as part of variable names (e.g., SetRoutingMode was properly updated).
  • Suggestion: Ensure all instances of Mode related to routing are consistently updated to RoutingMode to prevent confusion.
  • Example:
    // Before change
    public Agent SetAgentMode(string mode)
    // After change
    public Agent SetRoutingMode(string? mode)
    

Issue 2: Nullability and Serialization

  • Description: The Mode property in the Agent class was nullable and had a JsonIgnore condition added, but the change wasn't consistently applied to all other related properties where nullability should be considered.
  • Suggestion: Ensure all nullable properties are properly handled in JSON serialization and in method logic.

Issue 3: Error Logging and Debugging

  • Description: In the logging logic for Redis check and other network operations, there are conditional compilation checks for DEBUG mode.
  • Suggestion: Consider using a more robust configuration management approach that doesn't rely solely on compilation flags.
  • Example:
    #if !DEBUG
        _logger.LogError...
    #endif

Issue 4: Dependency Injection and Optional Services

  • Description: Parts of the code use dependency injection with optional services where the service might be null. For instance, redis is checked again with _services.GetService.
  • Suggestion: While treating optional services, ensure that null checks are followed by meaningful defaults or exception handling to prevent null reference exceptions.

Overall Evaluation

The code changes enhance clarity and introduce needed flexibility but require some consistency improvements in adopting new naming conventions and handling nullability robustly. Also, the use of configuration files can streamline debugging and logging processes.

@Oceania2018 Oceania2018 merged commit 3dfb921 into SciSharp:master May 22, 2025
4 checks passed
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.

4 participants