Skip to content

Refactor FieldManager.Factory.cs to add thread-safe access to field creation - #275

Merged
AngeloTadeucci merged 3 commits into
masterfrom
semaphore-fieldmanager-factory
Oct 4, 2024
Merged

Refactor FieldManager.Factory.cs to add thread-safe access to field creation#275
AngeloTadeucci merged 3 commits into
masterfrom
semaphore-fieldmanager-factory

Conversation

@AngeloTadeucci

@AngeloTadeucci AngeloTadeucci commented Oct 3, 2024

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Introduced a locking mechanism for thread-safe access to map retrieval methods, enhancing reliability during concurrent access.
    • Enhanced management of bonus maps with automatic initialization upon creation.

These changes improve the reliability of the application, ensuring smoother performance during high-traffic scenarios.

@coderabbitai

coderabbitai Bot commented Oct 3, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce a ConcurrentDictionary<int, SemaphoreSlim> named mapLocks in the Factory class of the FieldManager, enabling thread-safe access to the Get methods. Semaphore locks are acquired before executing the logic to retrieve or create fields, ensuring synchronization when multiple players access the same map. Additionally, the SetBonusMapPortal method is modified to initialize bonus maps, enhancing the management of map portals.

Changes

File Path Change Summary
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Added ConcurrentDictionary<int, SemaphoreSlim> mapLocks and methods for semaphore management in Get methods. Introduced GetInternal methods for field retrieval.
Maple2.Server.Game/Manager/Field/FieldManager.State.cs Updated SetBonusMapPortal method to include initialization of the bonus map.

Assessment against linked issues

Objective Addressed Explanation
Implement field enter queue (#268) The changes do not implement a queue for handling multiple players entering the same map.

Possibly related PRs

  • Fix: Instance Field Creation #243: The changes in this PR also modify the Get methods in the FieldManager.Factory.cs file, indicating a direct relationship with the main PR's focus on enhancing thread safety in the same methods.

Poem

In fields where bunnies hop and play,
A semaphore now keeps chaos at bay.
With threads in line, they enter with glee,
No more instances, just one map for me! 🐇✨
Together we'll bounce, safe and sound,
In our happy fields, joy will abound!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (1)

36-36: Simplify SemaphoreSlim initialization

You can simplify the initialization of SemaphoreSlim by using its constructor that only requires the initial count when it's equal to the maximum count.

Replace the current initialization with:

- semaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1);
+ semaphore = new SemaphoreSlim(1);

This makes the code more concise without changing the behavior.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e6caf42 and 4e49481.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (2 hunks)
🔇 Additional comments (1)
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (1)

48-66: Ensure exception safety when refactoring

If you choose to refactor the Get methods to eliminate the semaphore, make sure that the Create method is thread-safe and handles concurrent calls appropriately. If Create can be called simultaneously by multiple threads for the same mapId, ensure that it does not result in duplicate fields or unintended side effects.

Consider verifying the thread safety of the Create method. Run the following script to search for any usages of shared resources within Create that may not be thread-safe:

Also applies to: 74-88

Comment thread Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Outdated
Comment thread Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Outdated
Comment thread Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4e49481 and 9e1f35e.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (6 hunks)
🔇 Additional comments (4)
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (4)

31-32: LGTM: Thread-safe lock management implemented

The addition of mapLocks as a ConcurrentDictionary<int, SemaphoreSlim> is a good approach for managing locks on a per-map basis. This implementation aligns well with the PR objective of adding thread-safe access to field creation.

Also applies to: 35-35


184-187: LGTM: Proper resource management and lock retrieval implemented

The changes to the Dispose method ensure that all semaphore locks are properly disposed of, preventing resource leaks. The new GetMapLock method provides a thread-safe way to retrieve or create semaphore locks for each map ID. These implementations contribute to the overall thread safety and resource management of the class.

Also applies to: 193-196


Line range hint 1-196: Summary: Thread-safe field creation implemented with some suggestions for improvement

The changes in this PR successfully address the issue of multiple players creating separate instances of the same non-instanced map by implementing thread-safe access to field creation. The use of ConcurrentDictionary for managing locks and SemaphoreSlim for synchronization is appropriate and aligns well with the PR objectives.

However, there are a few areas where the implementation could be improved:

  1. Ensure proper lock release in the Get methods by using try-finally blocks.
  2. Consider refactoring the lock management for better encapsulation and maintainability.

These improvements will further enhance the thread safety and reliability of the field creation process. Overall, the PR makes significant progress towards resolving the issue described in #268.


71-73: ⚠️ Potential issue

Apply the same lock release pattern as suggested for the previous Get method

This method has the same lock management issue as the previous Get method. Please apply the same try-finally block pattern here to ensure proper lock release.

Comment thread Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Outdated
Comment thread Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (1)

182-210: LGTM with suggestion: Consider refactoring to reduce duplication

The new GetInternal methods correctly encapsulate the logic previously contained in the Get methods. This separation of concerns improves readability and maintainability of the code.

However, there's noticeable similarity between the two GetInternal methods. Consider refactoring to reduce this duplication. For example, you could create a single method that handles both cases:

private FieldManager? GetInternal(int mapId, long ownerId = 0, int instanceId = 0)
{
    if (!fields.TryGetValue(mapId, out OwnerFields? ownerFields))
    {
        return Create(mapId, ownerId: ownerId, instanceId: instanceId);
    }

    if (!ownerFields.TryGetValue(ownerId, out InstancedFields? instancedFields))
    {
        return Create(mapId, ownerId: ownerId, instanceId: instanceId);
    }

    return instancedFields.TryGetValue(instanceId, out FieldManager? field) ? field :
        Create(mapId, ownerId: ownerId, instanceId: instanceId);
}

This refactoring would eliminate the need for two separate methods while maintaining the same functionality.

Maple2.Server.Game/Manager/Field/FieldManager.State.cs (3)

454-454: LGTM! Consider adding error logging.

The addition of bonusMap?.Init(); is a good practice to ensure the bonus map is properly initialized before use. This change aligns with the PR objectives to enhance thread safety in field creation.

Consider adding error logging if the bonus map creation fails. This can be done by modifying the code as follows:

-bonusMap?.Init();
+if (bonusMap != null)
+{
+    bonusMap.Init();
+}
+else
+{
+    Log.Error("Failed to create bonus map {MapId}", bonusMapMetadata.Id);
+}

This change will provide better visibility into potential issues during bonus map creation.


Line range hint 451-459: Consider improving error handling for bonus map creation

The current implementation handles the case where bonus map creation fails, but it continues to create a portal even if the bonus map is null. This could lead to a portal that doesn't lead anywhere.

Consider refactoring the code to return early if the bonus map creation fails:

 MapMetadata bonusMapMetadata = bonusMaps[Random.Shared.Next(bonusMaps.Count)];
 FieldManager? bonusMap = FieldFactory.Create(bonusMapMetadata.Id);
 bonusMap?.Init();
 Console.WriteLine($"Creating bonus map {bonusMapMetadata.Id} at {spawn.Position} in {delay} ms.");
 if (bonusMap == null) {
+    Log.Error("Failed to create bonus map {MapId}", bonusMapMetadata.Id);
+    Scheduler.Schedule(() => SetBonusMapPortal(bonusMaps, spawn), delay);
     return;
 }
 bonusMap.SetRoomTimer(RoomTimerType.Clock, 90000);

This change ensures that we don't create a portal for a non-existent bonus map, while still scheduling the next attempt to create a bonus map.


Line range hint 1-1000: Well-structured class with good thread-safety practices

The FieldManager class is well-structured and implements good practices for thread-safety, such as using concurrent collections and nullable reference types. This aligns well with the PR objectives of enhancing thread safety in field creation.

For consistency, consider using the null-conditional operator ?. in other similar situations throughout the class. For example, in the RemoveNpc method:

 public bool RemoveNpc(int objectId, int removeDelay = 0) {
     if (!Mobs.TryRemove(objectId, out FieldNpc? npc) && !Npcs.TryRemove(objectId, out npc)) {
         return false;
     }

     Scheduler.Schedule(() => {
         Broadcast(FieldPacket.RemoveNpc(objectId));
         Broadcast(ProxyObjectPacket.RemoveNpc(objectId));
-        npc.Dispose();
+        npc?.Dispose();
     }, removeDelay);
     return true;
 }

This change would make the code more consistent with the null-safety practices used elsewhere in the class.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9e1f35e and 028e2cc.

📒 Files selected for processing (2)
  • Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (3 hunks)
  • Maple2.Server.Game/Manager/Field/FieldManager.State.cs (1 hunks)
🔇 Additional comments (7)
Maple2.Server.Game/Manager/Field/FieldManager.Factory.cs (7)

31-32: LGTM: Thread-safe lock management implemented

The addition of mapLocks as a ConcurrentDictionary<int, SemaphoreSlim> is a good approach for managing locks on a per-map basis. This implementation allows for efficient concurrent access and helps address the issue of multiple players entering the same non-instanced map simultaneously.


35-35: LGTM: Proper initialization of mapLocks

The initialization of mapLocks in the constructor is correct and necessary. This ensures that the lock management system is ready for use as soon as the Factory instance is created.


47-55: LGTM: Proper implementation of thread-safe field retrieval

The changes to the Get method effectively implement thread-safe access to field creation:

  1. The lock is correctly acquired using GetMapLock(mapId).
  2. The try-finally block ensures that the lock is always released, even if an exception occurs.
  3. Moving the logic to a separate GetInternal method improves code organization and readability.

These changes directly address the issue of multiple players creating separate instances when entering the same non-instanced map simultaneously.


64-72: LGTM: Consistent implementation of thread-safety in overloaded Get method

The changes in this overloaded Get method mirror those in the previous method, ensuring consistent thread-safe behavior:

  1. The lock is acquired using GetMapLock(mapId).
  2. The try-finally block is used to guarantee lock release.
  3. The logic is delegated to a separate GetInternal method.

This consistency across method overloads is crucial for maintaining uniform behavior and thread-safety throughout the class.


169-172: LGTM: Proper disposal of SemaphoreSlim instances

The addition of the loop to dispose of all SemaphoreSlim instances in mapLocks is a crucial step in preventing resource leaks. This ensures that all system resources associated with the semaphores are properly released when the Factory is disposed.


178-180: LGTM: Efficient and thread-safe lock management

The GetMapLock method is well-implemented:

  1. It uses GetOrAdd to ensure thread-safe creation of new locks when needed.
  2. It efficiently manages the creation and retrieval of locks for each map ID.
  3. The method encapsulates the lock management logic, promoting code reusability and maintainability.

This implementation supports the overall goal of ensuring thread-safe access to field creation.


Line range hint 1-238: Summary: Effective implementation of thread-safe field creation

The changes in this PR successfully address the issue of multiple players creating separate instances when entering the same non-instanced map simultaneously. Key improvements include:

  1. Introduction of a ConcurrentDictionary<int, SemaphoreSlim> for efficient, thread-safe lock management.
  2. Implementation of locking mechanisms in the Get methods to ensure thread-safe access to field creation.
  3. Proper disposal of SemaphoreSlim instances to prevent resource leaks.
  4. Encapsulation of lock management and field retrieval logic in separate methods for improved code organization.

These changes effectively meet the objectives outlined in the PR and linked issue #268. The code is well-structured and maintainable, with only a minor suggestion for refactoring to reduce duplication in the GetInternal methods.

Overall, this PR represents a significant improvement in the thread-safety and reliability of the field creation process.

@AngeloTadeucci
AngeloTadeucci merged commit a3ddd29 into master Oct 4, 2024
AngeloTadeucci added a commit that referenced this pull request Oct 4, 2024
@AngeloTadeucci
AngeloTadeucci deleted the semaphore-fieldmanager-factory branch October 4, 2024 17:19
@coderabbitai coderabbitai Bot mentioned this pull request May 29, 2025
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.

Implement field enter queue

2 participants