Skip to content

Multiple fixes - #358

Merged
AngeloTadeucci merged 5 commits into
masterfrom
dev
Mar 11, 2025
Merged

Multiple fixes#358
AngeloTadeucci merged 5 commits into
masterfrom
dev

Conversation

@AngeloTadeucci

@AngeloTadeucci AngeloTadeucci commented Mar 10, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced inventory sorting to prevent runtime errors.
    • Improved item drop processing to correctly handle bound items.
    • Refined home banking and guided navigation, ensuring smoother transitions.
    • Optimized selection and migration of game channels.
    • Strengthened item spawning with immediate data persistence for enhanced reliability.
  • New Features

    • Introduced a startup option to enable instanced content.
  • Tests

    • Expanded test coverage to verify correct sorting of inventory across various scenarios.
    • Added new tests for sorting functionality in the item collection.

@coderabbitai

coderabbitai Bot commented Mar 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request applies several improvements across the Maple2 server code. In the game manager and packet handler modules, loop conditions, command enum values, and conditional checks have been refined to prevent runtime errors and ensure proper control flow. The changes also add thread safety and immediate database persistence when spawning items, adjust channel lookup and migration logic in the world service, and introduce a command-line override for instanced content. Additional tests have been added to verify the sorting behavior of item collections without altering public interfaces.

Changes

File(s) Change Summary
Maple2.Server.Game/.../ItemCollection.cs
Maple2.Server.Tests/.../ItemCollectionTest.cs
Updated sorting logic in ItemCollection: fixed loop condition to avoid out-of-range errors and added tests for full inventory sorting, handling null slots, and post-removal sorting.
Maple2.Server.Game/.../HomeBankHandler.cs
Maple2.Server.Game/.../ItemInventoryHandler.cs
Maple2.Server.Game/.../MasteryHandler.cs
Maple2.Server.Game/.../QuestHandler.cs
Revised handler logic: updated command enum values and default parameter in HomeBank; added a bound item check in drop handling; simplified quest state verification in crafting; and introduced early migration for the default home map.
Maple2.Server.Game/Program.cs Introduced an override flag for instanced content via a command-line parameter, affecting the InstancedContent flag in channel requests.
Maple2.Server.World/.../ChannelClientLookup.cs
Maple2.Server.World/.../WorldService.Migrate.cs
Refined channel lookup and migration logic: added a condition for matching instanced content and improved error reporting for unavailable game channels.
Maple2.Server.Game/.../FieldManager.State.cs Enhanced SpawnItem by adding a thread-safe lock and invoking a SaveItems call for immediate database persistence when an item is spawned.

Sequence Diagram(s)

sequenceDiagram
    participant Session
    participant QuestHandler
    participant GameInstance

    Session->>QuestHandler: Send MapleGuide command with metadata
    QuestHandler->>QuestHandler: Check if GoToMapId == DefaultHomeMapId
    alt Is DefaultHomeMapId
         QuestHandler->>Session: MigrateToInstance(DefaultHomeMapId)
         QuestHandler-->>Session: Return early
    else Not DefaultHomeMapId
         QuestHandler->>QuestHandler: Prepare field enter packet
         QuestHandler->>Session: Send enter packet
    end
Loading
sequenceDiagram
    participant Request
    participant WorldService
    participant ChannelService

    Request->>WorldService: Initiate MigrateOut(request)
    alt request.InstancedContent is true
       WorldService->>ChannelService: Retrieve instanced channel ID
       alt Channel is active?
          WorldService->>WorldService: Assign channel for migration
       else
          WorldService->>Request: Throw RpcException ("No available instanced game channel")
       end
    else
       alt Specified channel is active?
          WorldService->>WorldService: Use specified channel
       else
          WorldService->>ChannelService: Find first available channel
          alt Channel found
             WorldService->>WorldService: Assign channel
          else
             WorldService->>Request: Throw RpcException ("No available game channels")
          end
       end
    end
Loading

Suggested reviewers

  • Zintixx

Poem

I'm a little rabbit, hopping through the code,
With loops now safe and channels in a mode.
My carrot tests are crunchy and true,
Each fix a joyful hop in skies so blue.
I nibble on bugs and dance with delight,
Celebrating changes from morning till night!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 10b5543 and f79d3ae.

📒 Files selected for processing (4)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (0 hunks)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: format
  • GitHub Check: build

🪧 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.
  • @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: 1

🧹 Nitpick comments (1)
Maple2.Server.Game/PacketHandlers/MasteryHandler.cs (1)

84-89: Logic flow improved for quest requirement validation

The conditional logic has been simplified and improved. Instead of checking both the quest existence and completion state, the code now uses a more straightforward approach: if the quest exists in the player's quest log, continue to the next quest; otherwise, send an error.

This change enhances readability and reduces nesting. However, there's a potential logic change - the old code may have been verifying quest completion status as well, whereas now it's only verifying quest existence.

Consider adding a comment to clarify the intended behavior here:

foreach (int questId in entry.RequiredQuests) {
+   // Only check if player has the quest in their log, not its completion status
    if (session.Quest.TryGetQuest(questId, out _)) continue;
    
    session.Send(MasteryPacket.Error(MasteryError.s_mastery_error_lack_quest));
    return;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 127e21e and ab238dd.

📒 Files selected for processing (10)
  • Maple2.Server.Game/Manager/Items/InventoryManager.cs (1 hunks)
  • Maple2.Server.Game/Manager/Items/ItemCollection.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/HomeBankHandler.cs (2 hunks)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/MasteryHandler.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/QuestHandler.cs (1 hunks)
  • Maple2.Server.Game/Program.cs (1 hunks)
  • Maple2.Server.Tests/Game/Manager/Item/ItemCollectionTest.cs (2 hunks)
  • Maple2.Server.World/Containers/ChannelClientLookup.cs (1 hunks)
  • Maple2.Server.World/Service/WorldService.Migrate.cs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: format
  • GitHub Check: build
🔇 Additional comments (19)
Maple2.Server.Game/Program.cs (2)

42-43: Command-line argument added for instanced content control

Adding a parameter to force instanced content mode is a good enhancement that improves flexibility when starting the server.


52-52: Correctly implements the instanced content override

The use of logical OR here is appropriate - it ensures that InstancedContent will be true either when the flag is provided or when it's configured in Target.InstancedContent.

Maple2.Server.World/Containers/ChannelClientLookup.cs (1)

70-70: Fixed channel selection logic for instanced content

This change properly fixes the fallback mechanism by ensuring that channels are matched not only by IP address and inactive status but also by their instanced content property. This prevents mismatches between instanced and non-instanced channels during migration.

Maple2.Server.World/Service/WorldService.Migrate.cs (5)

6-6: Appropriate addition of Core.Helpers namespace

This import is needed for the ChannelClientCollection extension methods used later in the file, notably TryGetInstancedChannelId and FirstChannel.


36-41: Improved handling for instanced content channels

The new code correctly prioritizes instanced channels when request.InstancedContent is true, and provides a clear error message when no instanced game channels are available. This enhances the robustness of the migration process.


41-43: Clear fallback logic for explicit channel requests

This conditional block properly handles the case when a specific channel is requested and available, providing a logical fallback path for non-instanced content.


44-49: Enhanced fallback mechanism with proper error handling

The fallback to the first available channel is now clearly documented with a comment, and includes proper error handling when no channels are available. The channel initialization is properly handled in all code paths.


52-52: Improved error message specificity

The error message now includes the channel number, which makes debugging easier by providing more specific information about which channel couldn't be found.

Maple2.Server.Tests/Game/Manager/Item/ItemCollectionTest.cs (4)

260-265: Code formatting improved for readability

The array initialization in the CollectionAssert is now properly formatted with each item on a separate line, improving readability.


267-298: Good addition of test for full inventory sorting

This test validates that sorting works correctly when the inventory is at maximum capacity. This is important since the related bug fix in ItemCollection.Sort() addresses boundary conditions.


300-323: Good test for sorting with null items (gaps)

This test ensures that sorting works correctly when there are gaps (null slots) in the inventory, validating that null items don't affect the sorting behavior. The test effectively verifies that items are properly compacted to the beginning of the collection.


325-355: Good test for sorting after removing an item

This test verifies that sorting correctly handles the case where an item has been removed from the collection, creating a gap. This helps validate the bug fix in the Sort method that prevents IndexOutOfRangeException.

Maple2.Server.Game/Manager/Items/InventoryManager.cs (1)

653-655: Good addition of utility method for marking items for deletion

This new method encapsulates the functionality of adding an item to the deletion list, improving code organization by providing a dedicated public API instead of directly accessing the delete list from outside classes.

This method aligns with the existing pattern in the class where delete.Add() is encapsulated by the Discard method, but provides an alternative when you want to mark an item for deletion without the additional logic in Discard.

Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (2)

111-111: Bound items now properly discarded

The condition has been expanded to also discard items that have the TransferFlag.Bind flag set. This ensures bound items are handled correctly when dropped, preventing potential exploits that could bypass binding restrictions.


116-116: Item tracking improved with deletion marking

The new call to AddItemToDelete marks the item for deletion before it's spawned in the field, which helps with inventory management and ensures consistent state tracking. This likely addresses issue #353 mentioned in the PR objectives about bank safe functionality.

Maple2.Server.Game/PacketHandlers/QuestHandler.cs (1)

204-207: Special handling for default home map migration

This new condition provides specialized handling when the destination map is the default home map. By migrating directly to an instanced version of the home map, the code ensures that players are correctly placed in their personal home instance rather than a shared map.

This change aligns with the PR objective of fixing "the fallback mechanism to the first available channel when migrating instances."

Maple2.Server.Game/PacketHandlers/HomeBankHandler.cs (3)

14-15: Updated enum values for bank commands

The command values for Home and Premium have been updated, likely to match the client's expected command values. This change helps ensure correct packet handling and prevents potential misinterpretation of commands.


31-31: Simplified premium bank access

The call to HomeBank() for the Premium command has been simplified by removing the time parameter, as premium bank access doesn't need the cooldown time tracking that the regular home bank requires.


36-36: Enhanced method flexibility with default parameter

The HomeBank method now includes a default parameter value, making it more flexible and allowing for cleaner code when the time parameter isn't needed (as in the Premium case). This is a good refactoring that simplifies the code while maintaining backward compatibility.

Comment thread Maple2.Server.Game/Manager/Items/ItemCollection.cs
Comment thread Maple2.Server.Game/Manager/Items/InventoryManager.cs Outdated
session.Send(MasteryPacket.Error(MasteryError.s_mastery_error_lack_quest));
return;
}
if (session.Quest.TryGetQuest(questId, out _)) continue;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

isnt this supposed to be the reverse?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

If it found a quest, then it's fine. If not send error

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

then it should break, ya? instead of continue

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

If we break we won't check the next quests. If it loops through all quests and they are found we can keep going, if any of them are not found then we send the error and exit early

@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

🧹 Nitpick comments (1)
Maple2.Server.Game/Manager/Field/FieldManager/FieldManager.State.cs (1)

199-202: Improved thread safety and database persistence when spawning items.

The changes add two important improvements:

  1. Thread safety through locking the item object during database operations
  2. Immediate persistence of spawned items to the database

This fixes potential race conditions and ensures items aren't lost during server restarts or instance migrations, which appears to address the bank safe functionality issue mentioned in the PR objectives.

However, the hardcoded 0 parameter in db.SaveItems(0, item) could benefit from clarification:

- db.SaveItems(0, item);
+ // The first parameter (0) represents [explanation of what 0 means]
+ db.SaveItems(0, item);

Or consider using a named constant instead of the magic number.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ab238dd and 76ab562.

📒 Files selected for processing (2)
  • Maple2.Server.Game/Manager/Field/FieldManager/FieldManager.State.cs (2 hunks)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs
🔇 Additional comments (1)
Maple2.Server.Game/Manager/Field/FieldManager/FieldManager.State.cs (1)

6-6: Required import added for database operations.

The addition of the Maple2.Database.Storage namespace import is necessary to support the new database persistence functionality in the SpawnItem method.

Comment thread Maple2.Server.Game/PacketHandlers/ItemInventoryHandler.cs Outdated
Co-authored-by: Zin <62830952+Zintixx@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants