Skip to content
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

Instancing Rework #510

Draft
wants to merge 16 commits into
base: next
Choose a base branch
from
Draft

Instancing Rework #510

wants to merge 16 commits into from

Conversation

Desoroxxx
Copy link
Collaborator

@Desoroxxx Desoroxxx commented Oct 25, 2024

📝 Description

This aims at reworking instancing, as of now, not in major ways, simply taking current systems and refining them / making them sane.

🎯 Goals

  • Make the instancing system cleaner
  • Make the instancing system simpler
  • Fix any issues related to the instancing system

❌ Non Goals

  • Rework the instancing system in fundamental ways

🚦 Testing

Currently testing is done in single player by shooting and doing any actions a player could do, also there are terrorist and soldiers.

⏮️ Backwards Compatibility

Weapons will reset

📚 Related Issues & Documents

#248

📖 Added to documentation?

  • 📜 README.md
  • 📑 Documentation
  • 📓 Javadoc
  • 🍕 Comments
  • 🙅 No documentation needed

😄 What gif best describes this PR or how it makes you feel?

Copy link
Contributor

@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: 11

🧹 Outside diff range and nitpick comments (20)
src/main/java/com/paneedah/mwc/commands/client/ClientCommandBase.java (1)

10-16: Enhance class documentation with usage guidelines.

While the current documentation provides basic information, consider adding:

  • Purpose and use cases for client-side commands
  • Security implications of unrestricted permissions
  • Guidelines for implementing derived classes
src/main/java/com/paneedah/mwc/commands/MWCCommand.java (2)

13-17: Enhance class-level documentation

The current documentation only specifies the author and version. Consider adding:

  • A description of the command's purpose
  • Available subcommands and their functions
  • How this command relates to the instancing system

Example enhancement:

 /**
+ * Main command handler for Modern Warfare Cubed mod that manages client-side functionality.
+ * Provides subcommands for managing player item instance registry and related operations.
+ *
  * @author Luna Mira Lage (Desoroxxx)
  * @since 0.2
  */

36-44: Consider enhancing the usage message

While the permission level is appropriate for client-side commands, the usage message could be more helpful.

Consider enhancing the usage message to list available subcommands:

 @Override
 public String getUsage(ICommandSender sender) {
-    return "/" + ID + " <subcommand>";
+    return "/" + ID + " <playeriteminstanceregistry> - Manages player item instances";
 }
src/main/java/com/paneedah/weaponlib/PlayerMagazineInstance.java (1)

Line range hint 17-17: Consider cleaning up commented-out code.

There are several blocks of commented-out code related to ammo management. If this functionality is:

  • Work in progress: Convert to TODO comments with implementation plans
  • Deprecated: Remove it and track in version control history
  • Debug code: Remove it as it adds noise

This will improve code maintainability and readability.

Also applies to: 40-40, 41-41, 42-42, 43-43, 44-44

src/main/java/com/paneedah/mwc/commands/client/CommandPlayerItemInstanceRegistry.java (1)

14-18: Enhance class-level documentation.

While the basic Javadoc is present, consider adding a description of the class's purpose and responsibilities. This would help other developers understand when and how to use this command registry.

 /**
+ * Command handler for managing the player item instance registry.
+ * Provides subcommands for cache invalidation and registry clearing operations.
+ *
  * @author Luna Mira Lage (Desoroxxx)
  * @since 0.2
  */
src/main/java/com/paneedah/mwc/handlers/ClientEventHandler.java (1)

Line range hint 45-71: Consider refactoring for better separation of concerns.

The onRenderGameOverlayEvent method handles multiple responsibilities: registry management, queue processing, and item rendering. This makes the code harder to maintain and test.

Consider splitting this into separate methods:

     @SubscribeEvent
     public static void onRenderGameOverlayEvent(RenderGameOverlayEvent.Pre renderGameOverlayEvent) {
         if (cooked) {
             return;
         }
 
         if (COOKING_QUEUE.isEmpty()) {
             cooked = true;
-            MWC.modContext.getPlayerItemInstanceRegistry().clearRegistry();
-            MWC.modContext.getPlayerItemInstanceRegistry().invalidateCache();
+            cleanupRegistryAndCache();
         }
 
+        processRenderQueue();
+    }
+
+    private static void cleanupRegistryAndCache() {
+        MWC.modContext.getPlayerItemInstanceRegistry().clearRegistry();
+        MWC.modContext.getPlayerItemInstanceRegistry().invalidateCache();
+    }
+
+    private static void processRenderQueue() {
         for (int i = 0; i < 32 && !COOKING_QUEUE.isEmpty(); i++) {
             final Item item = COOKING_QUEUE.poll();
 
             if (item != null) {
                 MC.getRenderItem().renderItem(new ItemStack(item), ItemCameraTransforms.TransformType.GUI);
             }
         }
-    }
src/main/java/com/paneedah/weaponlib/electronics/ItemTablet.java (1)

77-81: LGTM! Consider adding Javadoc for better documentation.

The changes improve code quality by:

  • Adding final modifiers to prevent accidental parameter modifications
  • Using more descriptive parameter names that better indicate their purpose

Consider adding Javadoc to document the parameters:

/**
 * Creates a new tablet instance for the given entity.
 *
 * @param entityLivingBase the entity that will own this tablet instance
 * @param itemStack the item stack representing this tablet
 * @param slot the inventory slot containing this tablet
 * @return a new PlayerTabletInstance initialized in READY state
 */
public PlayerTabletInstance createItemInstance(final EntityLivingBase entityLivingBase, 
    final ItemStack itemStack, final int slot) {
src/main/java/com/paneedah/weaponlib/RenderContext.java (1)

156-160: Consider adding null checks for improved robustness.

While the current implementation works, consider adding null checks for both player and itemStack before accessing the registry to prevent potential NPEs in edge cases.

Here's a suggested improvement:

     public PlayerWeaponInstance getWeaponInstance() {
         if (playerItemInstance instanceof PlayerWeaponInstance) {
             return (PlayerWeaponInstance) playerItemInstance;
         }
+        if (player == null || itemStack == null) {
+            return null;
+        }
         PlayerItemInstance<?> itemInstance = MWC.modContext.getPlayerItemInstanceRegistry()
                 .getCachedItemInstance(player, itemStack);
         if (itemInstance instanceof PlayerWeaponInstance) {
src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java (2)

Line range hint 92-108: Consider documenting the new state management behavior.

While the implementation is cleaner, and the comment explains why the change was made, it would be beneficial to document the new expected behavior for future maintainers.

Consider adding a Javadoc comment like:

/**
 * Sets the state and updates the timestamp. If a prepared state exists,
 * it will be committed and cleared.
 * 
 * @param state The new state to set
 * @return false as the state change is always accepted in this implementation
 */

Line range hint 141-153: Document the magazine swap lifecycle.

The new magazine swap functionality would benefit from documentation explaining:

  • When these methods are called in the swap lifecycle
  • The relationship between completeMagSwap, markMagSwapReady, and isMagSwapDone
  • Any threading considerations

Consider adding Javadoc comments to explain the lifecycle:

/**
 * Marks the magazine swap as complete. This should be called after
 * all swap-related animations and state changes are finished.
 */
public void completeMagSwap() {
    this.compoundMagSwapCompleted = true;
}

/**
 * Resets the magazine swap state to prepare for a new swap operation.
 * This should be called before initiating a new magazine swap.
 */
public void markMagSwapReady() {
    this.compoundMagSwapCompleted = false;
}

/**
 * @return true if the current magazine swap operation has completed
 */
public boolean isMagSwapDone() {
    return this.compoundMagSwapCompleted;
}
src/main/java/com/paneedah/mwc/renderer/StaticModelSourceRenderer.java (1)

268-268: LGTM! Consider documenting cache behavior.

The switch to getCachedItemInstance aligns with the PR's optimization goals. This change should improve performance by reducing instance creation overhead.

Consider adding a comment explaining:

  • Cache lifetime/invalidation strategy
  • Thread-safety guarantees
  • Impact on memory usage
Changelog.md (2)

53-55: Documentation needs improvement for new commands.

The new commands would benefit from additional documentation:

  1. Explain what "CCS" means
  2. Document when users should use these commands
  3. Consider adding shorter command aliases for better usability

Add documentation like this:

 - Added two new commands to fix CCS when it happens
+    These commands help fix Client Cache Synchronization (CCS) issues that may occur when weapon instances become desynchronized:
   - `/mwc playeriteminstanceregistry invalidateitemstackinstancecache`
+      Use this command when weapon appearances are incorrect
   - `/mwc playeriteminstanceregistry clearregistry`
+      Use this command when weapons stop working entirely

88-91: Enhance optimization documentation with performance details.

The optimization section would benefit from additional context:

  1. Specify when exactly during "first world load" these operations occur
  2. Document the performance impact and benefits
  3. Explain why these optimizations are necessary

Add details like this:

 ### Optimization
 
-Clear player item instance registry after rendering every weapon once on first world load
-Invalidate player item instance registry itemstack instance cache after rendering every weapon once on first world load
+- Clear player item instance registry after rendering every weapon once on first world load
+  - Reduces memory usage by cleaning up unused weapon instances
+  - Occurs after initial weapon model loading is complete
+- Invalidate player item instance registry itemstack instance cache after rendering every weapon once on first world load
+  - Ensures accurate weapon rendering by refreshing the cache
+  - Prevents visual glitches that may occur from stale cache data
src/main/java/com/paneedah/weaponlib/WeaponAttachmentAspect.java (2)

Line range hint 227-229: Clarify the purpose of the zero index check.

The comment "is this a bug?" suggests uncertainty about the purpose of skipping zero indices. Consider either:

  1. Documenting why zero indices should be skipped
  2. Adding validation to ensure zero indices never occur

Line range hint 202-241: Consider enhancing error handling.

The method could benefit from more explicit error handling:

  1. Add validation for null activeAttachmentsIds
  2. Consider throwing specific exceptions for invalid attachment configurations
  3. Add logging for debugging invalid states

Example enhancement:

 PlayerItemInstance<?> itemInstance = modContext.getPlayerItemInstanceRegistry().getCachedItemInstance(player,
         itemStack);

+if (itemInstance == null) {
+    LOGGER.warn("No item instance found for player {} and item {}", player, itemStack);
+    return Collections.emptyList();
+}

 int[] activeAttachmentsIds;
 if (!(itemInstance instanceof PlayerWeaponInstance)) {
src/main/java/com/paneedah/weaponlib/WeaponReloadAspect.java (2)

139-139: Ensure consistent timestamp usage in compound reload completion

The change to use getReloadUpdateTimestamp() in shouldFinishCompoundReload aligns with the previous change, maintaining consistency in timestamp handling across reload states.

Consider documenting the difference between getReloadTimestamp() and getReloadUpdateTimestamp() in the class documentation to clarify their specific purposes and when each should be used.


Line range hint 1-1000: Consider implementing a state machine pattern for better maintainability

The class contains complex state management logic with numerous state transitions and conditions. While functional, it could benefit from a more structured approach.

Consider refactoring the state management using a proper state machine pattern:

  1. Create separate classes for each weapon state
  2. Encapsulate transition logic within state classes
  3. Use a state machine library or implement a simple state machine framework

This would:

  • Improve code maintainability
  • Make state transitions more explicit
  • Reduce the complexity of the WeaponReloadAspect class
  • Make it easier to add new states or modify existing ones
src/main/java/com/paneedah/weaponlib/Weapon.java (1)

1422-1424: Add braces to if statement for better maintainability.

While removing braces from single-line if statements is syntactically valid, it can lead to bugs when the code is modified in the future. Consider adding braces back:

-            if (compatibleAttachment.isDefault() && attachment.getApply2() != null)
-                attachment.apply2.apply(attachment, instance);
+            if (compatibleAttachment.isDefault() && attachment.getApply2() != null) {
+                attachment.apply2.apply(attachment, instance);
+            }
src/main/java/com/paneedah/weaponlib/WeaponRenderer.java (2)

2306-2306: Performance improvement: Using cached item instance retrieval

The change from getItemInstance to getCachedItemInstance improves performance by avoiding redundant instance creation during first-person rendering.

This optimization is particularly important for first-person rendering which happens frequently during gameplay. The caching mechanism helps reduce GC pressure and CPU usage.


2522-2522: Consistent caching implementation for third-person rendering

The same caching optimization is correctly applied to third-person rendering, maintaining consistency with the first-person implementation.

The consistent implementation across both rendering modes ensures the caching benefits are available regardless of perspective, while keeping the codebase maintainable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ae0eab7 and f62529e.

📒 Files selected for processing (34)
  • Changelog.md (2 hunks)
  • src/main/java/com/paneedah/mwc/MWC.java (3 hunks)
  • src/main/java/com/paneedah/mwc/commands/MWCCommand.java (1 hunks)
  • src/main/java/com/paneedah/mwc/commands/client/ClientCommandBase.java (1 hunks)
  • src/main/java/com/paneedah/mwc/commands/client/ClientCommandTreeBase.java (1 hunks)
  • src/main/java/com/paneedah/mwc/commands/client/CommandPlayerItemInstanceRegistry.java (1 hunks)
  • src/main/java/com/paneedah/mwc/handlers/ClientEventHandler.java (2 hunks)
  • src/main/java/com/paneedah/mwc/handlers/DebugHandler.java (2 hunks)
  • src/main/java/com/paneedah/mwc/renderer/StaticModelSourceRenderer.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/ClientEventHandler.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/ItemMagazine.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java (4 hunks)
  • src/main/java/com/paneedah/weaponlib/PlayerItemInstanceFactory.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/PlayerItemInstanceRegistry.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/PlayerMagazineInstance.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/PlayerWeaponInstance.java (2 hunks)
  • src/main/java/com/paneedah/weaponlib/RenderContext.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/SyncManager.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/Weapon.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/WeaponAttachmentAspect.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/WeaponEventHandler.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/WeaponReloadAspect.java (2 hunks)
  • src/main/java/com/paneedah/weaponlib/WeaponRenderer.java (3 hunks)
  • src/main/java/com/paneedah/weaponlib/electronics/ItemHandheld.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/electronics/ItemTablet.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/electronics/PlayerHandheldInstance.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/electronics/PlayerTabletInstance.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/grenade/GrenadeRenderer.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/grenade/ItemGrenade.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/grenade/PlayerGrenadeInstance.java (2 hunks)
  • src/main/java/com/paneedah/weaponlib/melee/ItemMelee.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/melee/MeleeAttachmentAspect.java (1 hunks)
  • src/main/java/com/paneedah/weaponlib/melee/MeleeRenderer.java (2 hunks)
  • src/main/java/com/paneedah/weaponlib/melee/PlayerMeleeInstance.java (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/main/java/com/paneedah/weaponlib/PlayerItemInstanceFactory.java
  • src/main/java/com/paneedah/weaponlib/PlayerWeaponInstance.java
🧰 Additional context used
🪛 ast-grep
src/main/java/com/paneedah/mwc/MWC.java

[warning] 89-89: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new MWCCommand())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 89-89: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new MWCCommand())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/mwc/commands/MWCCommand.java

[warning] 22-22: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new CommandPlayerItemInstanceRegistry())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 22-22: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new CommandPlayerItemInstanceRegistry())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/mwc/commands/client/CommandPlayerItemInstanceRegistry.java

[warning] 21-21: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new CommandInvalidateItemstackInstanceCache())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 22-22: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new CommandClearRegistry())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 51-51: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new TextComponentString("Invalidated itemstack instance cache"))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 71-71: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new TextComponentString("Cleared player item instance registry"))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 21-21: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new CommandInvalidateItemstackInstanceCache())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 22-22: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new CommandClearRegistry())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 51-51: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new TextComponentString("Invalidated itemstack instance cache"))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 71-71: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new TextComponentString("Cleared player item instance registry"))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/mwc/handlers/DebugHandler.java

[warning] 35-35: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (String.format("%s%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 35-35: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (String.format("%s%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

🪛 GitHub Check: CodeScene Cloud Delta Analysis (next)
src/main/java/com/paneedah/weaponlib/PlayerItemInstanceRegistry.java

[warning] 138-165: ❌ Getting worse: Complex Method
createItemInstance increases in cyclomatic complexity from 9 to 11, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.


[notice] 97-122: ✅ Getting better: Complex Method
getItemInstance decreases in cyclomatic complexity from 17 to 9, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.


[notice] 89-101: ✅ No longer an issue: Complex Method
getItemInstance is no longer above the threshold for cyclomatic complexity. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.


[notice] 222-322: ✅ No longer an issue: Complex Method
update is no longer above the threshold for cyclomatic complexity. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.


[warning] 182-218: ❌ New issue: Complex Method
getCachedItemInstance has a cyclomatic complexity of 14, threshold = 9. This function has many conditional statements (e.g. if, for, while), leading to lower code health. Avoid adding more conditionals and code to it without refactoring.


[notice] 212-212: ✅ No longer an issue: Complex Conditional
getItemInstance no longer has a complex conditional


[notice] 267-269: ✅ No longer an issue: Complex Conditional
update no longer has a complex conditional


[notice] 89-101: ✅ No longer an issue: Bumpy Road Ahead
getItemInstance is no longer above the threshold for logical blocks with deeply nested code. The Bumpy Road code smell is a function that contains multiple chunks of nested conditional logic. The deeper the nesting and the more bumps, the lower the code health.


[warning] 138-165: ❌ New issue: Bumpy Road Ahead
createItemInstance has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is one single, nested block per function. The Bumpy Road code smell is a function that contains multiple chunks of nested conditional logic. The deeper the nesting and the more bumps, the lower the code health.


[warning] 182-218: ❌ New issue: Bumpy Road Ahead
getCachedItemInstance has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is one single, nested block per function. The Bumpy Road code smell is a function that contains multiple chunks of nested conditional logic. The deeper the nesting and the more bumps, the lower the code health.


[notice] 89-101: ✅ No longer an issue: Deep, Nested Complexity
getItemInstance is no longer above the threshold for nested complexity depth

🔇 Additional comments (45)
src/main/java/com/paneedah/mwc/commands/client/ClientCommandTreeBase.java (2)

10-15: LGTM! Well-structured class with proper documentation.

The class is well-documented with author and version information, and the @SideOnly annotation correctly restricts it to client-side usage.


17-25: Verify client-side command security implications.

The permissive permission checks (returning 0 and true) are acceptable for client-side commands, but let's verify that this class is only extended by client-side command handlers to prevent potential security issues.

✅ Verification successful

Let me verify the package structure and annotations more thoroughly.


Client-side command security is properly enforced

The security implications have been verified:

  • ClientCommandTreeBase is properly annotated with @SideOnly(CLIENT)
  • It's located in the client package
  • Only one class extends it (CommandPlayerItemInstanceRegistry), which is also in the client package and annotated with @SideOnly(CLIENT)
  • The package structure shows clear separation between client and server commands

The permissive permission checks are safe in this context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that ClientCommandTreeBase is only used by client-side commands

# Test 1: Check for any classes extending ClientCommandTreeBase
echo "Checking for classes extending ClientCommandTreeBase..."
ast-grep --pattern 'class $_ extends ClientCommandTreeBase {
  $$$
}'

# Test 2: Verify these classes are properly annotated with @SideOnly(CLIENT)
echo "Verifying @SideOnly(CLIENT) annotation on implementations..."
rg -B 2 "extends ClientCommandTreeBase"

Length of output: 730


Script:

#!/bin/bash
# Check the full directory structure and content of client commands
echo "Checking client commands directory structure..."
fd . src/main/java/com/paneedah/mwc/commands/

# Check if ClientCommandTreeBase itself has the CLIENT annotation
echo "Checking ClientCommandTreeBase annotations..."
rg -B 3 "class ClientCommandTreeBase"

# Look for any other potential extensions outside the client package
echo "Looking for other extensions..."
rg "extends ClientCommandTreeBase" --type java

Length of output: 1322

src/main/java/com/paneedah/mwc/commands/client/ClientCommandBase.java (2)

1-28: LGTM! Clean and well-structured base class.

The implementation provides a solid foundation for client-side commands with:

  • Proper package organization
  • Clear separation of client-side concerns using @SideOnly
  • Consistent permission model

19-27: Verify the security implications of unrestricted permissions.

The implementation allows unrestricted access to derived commands by returning 0 for permission level and true for permission checks. While this might be intentional for client-side commands, we should verify that:

  1. This class is only used for safe, client-side operations
  2. No sensitive operations can be exposed through derived classes
✅ Verification successful

Let me analyze the security implications by checking the usage and inheritance of ClientCommandBase. I'll generate scripts to verify this.


Let me check the actual command implementations and their operations to verify if they are truly client-side only.


Based on the analysis, I can now provide a final response:

The unrestricted permissions in ClientCommandBase are safe and appropriate.

The implementation is secure because:

  1. All command classes are properly annotated with @SideOnly(CLIENT), ensuring they only execute on the client-side
  2. The only command implementation found (CommandPlayerItemInstanceRegistry) performs purely client-side operations:
    • Cache invalidation
    • Registry clearing
    • Local message display
  3. No server-side operations or network communications were found in any of the client command implementations
  4. The MinecraftServer parameter in checkPermission() is part of Minecraft's command interface but isn't used for any server operations

The permission level 0 and unrestricted checks are intentional and appropriate for client-side-only commands that cannot affect server state.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any sensitive operations in classes that extend ClientCommandBase

# Search for classes extending ClientCommandBase
echo "Checking for classes extending ClientCommandBase..."
ast-grep --pattern 'class $_ extends ClientCommandBase {
  $$$
}'

# Look for potential sensitive operations in these classes
echo "Checking for potential sensitive operations..."
rg -l "MinecraftServer|WorldServer|save|delete|op|ban|kick" $(fd -e java)

Length of output: 136447


Script:

#!/bin/bash

# Check for classes extending ClientCommandBase and their implementations
echo "=== Checking ClientCommandBase inheritance ==="
ast-grep --pattern 'class $_ extends ClientCommandBase {
  $$$
}'

# Look for command registration and usage
echo -e "\n=== Checking command registration and usage ==="
rg -l "registerCommand.*ClientCommandBase" 

# Check for any server-side operations in client command classes
echo -e "\n=== Checking for server operations in client commands ==="
rg -A 5 "MinecraftServer|WorldServer" src/main/java/com/paneedah/mwc/commands/client/

Length of output: 5095


Script:

#!/bin/bash

# Check command implementations and their operations
echo "=== Checking command implementations ==="
rg -A 10 "execute.*MinecraftServer" src/main/java/com/paneedah/mwc/commands/client/

# Check for @SideOnly(CLIENT) annotations to verify client-side enforcement
echo -e "\n=== Checking client-side enforcement ==="
rg "@SideOnly.*CLIENT" src/main/java/com/paneedah/mwc/commands/client/

# Look for any network or server-side operations
echo -e "\n=== Checking for network/server operations ==="
rg -l "sendToServer|sendPacketToServer|getServer|WorldServer" src/main/java/com/paneedah/mwc/commands/client/

Length of output: 3339

src/main/java/com/paneedah/mwc/commands/MWCCommand.java (2)

26-34: LGTM! Clean implementation of command identifiers

The implementation follows best practices by using constants and providing a clear alias with an immutable list.


1-45: Verify command registration

The command implementation looks good, but let's verify its registration.

✅ Verification successful

Command registration is properly implemented

The command is correctly registered via ClientCommandHandler.instance.registerCommand(new MWCCommand()) in the main mod class MWC.java.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for command registration in the codebase
rg "ClientCommandHandler.*registerCommand.*MWCCommand" -A 2

Length of output: 269

🧰 Tools
🪛 ast-grep

[warning] 22-22: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new CommandPlayerItemInstanceRegistry())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 22-22: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new CommandPlayerItemInstanceRegistry())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/weaponlib/PlayerMagazineInstance.java (1)

5-5: LGTM! Clean use of Lombok for constructor generation.

The addition of @NoArgsConstructor is a good refactoring that reduces boilerplate while maintaining the same functionality.

Also applies to: 9-9

src/main/java/com/paneedah/weaponlib/electronics/PlayerHandheldInstance.java (2)

7-7: LGTM! Good use of Lombok to reduce boilerplate.

The addition of @NoArgsConstructor is a clean way to replace the explicit no-args constructor while maintaining the same functionality. This change aligns well with the PR's goal of making the instancing system cleaner and simpler.

Also applies to: 11-11


11-11: Verify TypeRegistry compatibility with Lombok-generated constructor.

Since this class is registered with TypeRegistry for serialization/deserialization, let's verify that the Lombok-generated constructor maintains compatibility with the registration system.

Also applies to: 16-16

✅ Verification successful

Let me generate another verification script to check the TypeRegistry implementation and its requirements:

This will help us understand if TypeRegistry has any specific constructor requirements for serialization/deserialization and check the inheritance hierarchy of PlayerHandheldInstance.


Let me check one more aspect to verify the serialization interface implementation:


Based on the gathered information, I can now provide the final response:

@NoArgsConstructor is compatible with TypeRegistry serialization system

The Lombok-generated no-args constructor is safe to use because:

  • PlayerHandheldInstance extends PlayerItemInstance which already handles TypeRegistry registration
  • TypeRegistry only requires classes to be registered via register() method and doesn't impose any constructor constraints
  • The parent class PlayerItemInstance implements serialization through UniversalObject, making it compatible with the TypeRegistry system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any special constructor requirements in TypeRegistry
# or similar usage patterns in other registered classes

# Look for TypeRegistry usage patterns
rg -A 5 "TypeRegistry.*register\(" 

# Look for other classes using @NoArgsConstructor with TypeRegistry
ast-grep --pattern 'class $_ {
  $$$
  static {
    $$$TypeRegistry$$$register$$$
  }
  $$$
}'

Length of output: 14236


Script:

#!/bin/bash
# Check TypeRegistry implementation for constructor requirements
rg -A 10 "class TypeRegistry" 

# Look for deserialization usage
rg -A 5 "TypeRegistry.*deserialize"

# Check if PlayerHandheldInstance has any parent class
ast-grep --pattern 'class PlayerHandheldInstance extends $_ {
  $$$
}'

Length of output: 1147


Script:

#!/bin/bash
# Check if PlayerHandheldInstance implements ISerializable
ast-grep --pattern 'class PlayerHandheldInstance $_ implements $$$ISerializable$$$ {
  $$$
}'

# Check parent class PlayerItemInstance
rg -A 10 "class PlayerItemInstance"

# Look for serialization/deserialization methods
rg -A 5 "serialize|deserialize" src/main/java/com/paneedah/weaponlib/electronics/PlayerHandheldInstance.java

Length of output: 2586

src/main/java/com/paneedah/mwc/handlers/DebugHandler.java (2)

3-5: LGTM! Import statements are appropriate.

The new imports are correctly added and necessary for accessing the mod context and player item instance registry.


35-36: Verify cache size retrieval performance and add null check.

The debug information addition follows consistent formatting and provides valuable insights into the instance system. However, consider two improvements:

  1. Add a null check for MWC.modContext
  2. Consider caching the size value if performance becomes an issue during debug rendering

Let's verify the usage of modContext across the codebase:

Consider applying this defensive programming pattern:

-            debugScreenLeft.add(String.format("%s<MWC>%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()));
+            if (MWC.modContext != null && MWC.modContext.getPlayerItemInstanceRegistry() != null) {
+                debugScreenLeft.add(String.format("%s<MWC>%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()));
+            }
🧰 Tools
🪛 ast-grep

[warning] 35-35: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (String.format("%s%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 35-35: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (String.format("%s%s Itemstack instance cache size: %s", TextFormatting.GOLD, TextFormatting.RESET, MWC.modContext.getPlayerItemInstanceRegistry().getCacheSize()))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/weaponlib/electronics/ItemHandheld.java (2)

64-66: LGTM! Parameter naming improvements enhance code clarity.

The changes improve code readability through more descriptive parameter names and add immutability with final modifiers.


64-70: Verify consistent parameter naming across interface implementations.

Since this method implements PlayerItemInstanceFactory.createItemInstance, we should ensure consistent parameter naming across all implementations for maintainability.

✅ Verification successful

Parameter naming is consistent across all implementations

The verification shows that all implementations of createItemInstance use identical parameter names:

  • entityLivingBase
  • itemStack
  • slot

This consistency is maintained across all implementations found in:

  • Weapon.java
  • ItemMagazine.java
  • ItemMelee.java
  • ItemGrenade.java
  • ItemTablet.java
  • ItemHandheld.java
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all implementations of createItemInstance to verify naming consistency
# Expected: All implementations should use entityLivingBase and itemStack parameter names

# Search for interface implementations
ast-grep --pattern 'class $_ implements $$$PlayerItemInstanceFactory$$$'

# Search for createItemInstance method implementations
ast-grep --pattern 'createItemInstance(final EntityLivingBase $_, final ItemStack $_, $_) {
  $$$
}'

Length of output: 177


Script:

#!/bin/bash
# Let's try a different approach to find implementations

# First, let's find the interface definition
rg -l "interface.*PlayerItemInstanceFactory" --type java

# Then find all createItemInstance method signatures
rg "createItemInstance.*EntityLivingBase.*ItemStack" --type java -A 2

Length of output: 3014

src/main/java/com/paneedah/mwc/handlers/ClientEventHandler.java (3)

4-4: LGTM: Import statement is correctly added.

The MWC import is necessary for accessing the modContext and PlayerItemInstanceRegistry.


56-58: Review the architectural placement of registry operations.

The registry and cache operations are tied to a render event and a "cooking" mechanism, which seems like an unusual architectural choice. This could have performance implications and makes the code harder to maintain.

Consider:

  1. Moving these operations to a more appropriate lifecycle event
  2. Adding error handling for the registry operations
  3. Documenting why these operations need to happen at this specific point

Let's check the usage of these registry methods:

#!/bin/bash
# Search for clearRegistry and invalidateCache usage
rg "clearRegistry|invalidateCache" --type java -A 2 -B 2

Line range hint 27-29: Consider improving encapsulation and documentation of the cooking queue.

While the TODO comment references documentation, there are several concerns:

  1. The public static queue could be accessed and modified from anywhere
  2. The purpose and lifecycle of the "cooking" process isn't clear in the code

Let's check if this queue is accessed from other classes:

Consider:

  1. Making COOKING_QUEUE private and providing controlled access methods
  2. Adding JavaDoc explaining the purpose and lifecycle of the cooking process
  3. Using an immutable queue type or implementing thread-safe access if needed
-    public static final Queue<Item> COOKING_QUEUE = new ArrayDeque<>();
+    private static final Queue<Item> COOKING_QUEUE = new ArrayDeque<>();
+
+    /**
+     * Adds an item to the cooking queue for deferred rendering
+     * @param item The item to be processed
+     */
+    public static void queueItemForCooking(Item item) {
+        COOKING_QUEUE.offer(item);
+    }
src/main/java/com/paneedah/weaponlib/electronics/PlayerTabletInstance.java (2)

9-9: LGTM! Clean Lombok integration for serialization support.

The addition of @NoArgsConstructor is appropriate here as it:

  1. Supports TypeRegistry serialization requirements
  2. Maintains clean code by reducing boilerplate
  3. Preserves existing functionality

Also applies to: 15-15


15-15: Verify parent class compatibility with no-arg constructor.

Since this class is used for serialization (via TypeRegistry), ensure that PlayerItemInstance<TabletState> supports no-arg construction.

✅ Verification successful

@NoArgsConstructor usage is consistent with parent class and sibling classes

The parent class PlayerItemInstance and all other subclasses (PlayerWeaponInstance, PlayerMagazineInstance, PlayerMeleeInstance, PlayerGrenadeInstance, PlayerHandheldInstance) also use @NoArgsConstructor. This is consistent with the serialization requirements as all these classes are registered with TypeRegistry.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the parent class definition to verify no-arg constructor support
ast-grep --pattern 'class PlayerItemInstance {
  $$$
}'

# Also check if other subclasses of PlayerItemInstance use @NoArgsConstructor
rg "@NoArgsConstructor.*class.*extends.*PlayerItemInstance"

Length of output: 119


Script:

#!/bin/bash
# Try different pattern to find PlayerItemInstance class definition
ast-grep --pattern 'class PlayerItemInstance'

# Search for files containing PlayerItemInstance to locate the class
rg "class.*PlayerItemInstance" -A 5

# Search for any no-arg constructor in PlayerItemInstance
rg "PlayerItemInstance\(\)" -A 2

# Look for other instance classes to understand the pattern
fd "Instance.java" --exec rg "class.*extends.*PlayerItemInstance" {} -A 3

Length of output: 12267


Script:

#!/bin/bash
# Check for constructors in PlayerItemInstance class
rg "PlayerItemInstance.*\{" -A 10 src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java

# Check if other subclasses have @NoArgsConstructor
rg "@NoArgsConstructor" src/main/java/com/paneedah/weaponlib/

Length of output: 2375

src/main/java/com/paneedah/weaponlib/SyncManager.java (1)

61-65: Verify thread safety of direct field access.

The change from setter methods to direct field access for syncStartTimestamp might introduce thread safety issues if this class is accessed from multiple threads.

Let's check for potential concurrent access:

Additionally, consider adding synchronization if needed:

 private void sync(PlayerItemInstance<?> watchable) {
     LOGGER.debug("Syncing {} in state {} with update id {} to server", watchable, watchable.getState(), watchable.getUpdateId());
     long updateId = watchable.getUpdateId(); // capturing update id
-    watchable.syncStartTimestamp = System.currentTimeMillis();
+    synchronized(watchable) {
+        watchable.syncStartTimestamp = System.currentTimeMillis();
+    }
     permitManager.request(new Permit<>((S) watchable.getState()), (PlayerItemInstance<S>) watchable, (p, e) -> {
         // During sync, the watchable.getUpdateId() can change, so using the original update id
         watchables.put(watchable, updateId);
-        watchable.syncStartTimestamp = 0;
+        synchronized(watchable) {
+            watchable.syncStartTimestamp = 0;
+        }
         LOGGER.debug("Completed syncing {} with update id {}", watchable, updateId);
     });
 }
✅ Verification successful

Direct field access to syncStartTimestamp is safe in this context

The field access is thread-safe because:

  1. The syncStartTimestamp field is only accessed within the SyncManager class and its associated PlayerItemInstance
  2. The SyncManager.run() method is called from the server tick event (CommonEventHandler.onTick), which runs on the server thread
  3. The sync() method is only called from within the same run() method or through watch()/unwatch() operations
  4. The ClientTickerController that uses a separate thread only interacts with client-side logic and doesn't access this field
  5. The field is used as a simple timestamp marker for timeout detection, where small race conditions wouldn't impact functionality

The change from setter methods to direct field access is acceptable in this case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any concurrent/async usage patterns
rg -l "extends Thread|implements Runnable|ExecutorService|CompletableFuture|@Async|scheduleAtFixedRate" | while read -r file; do
    echo "=== $file ==="
    rg -A 5 "SyncManager" "$file"
done

Length of output: 359


Script:

#!/bin/bash
# Let's search for any concurrent access patterns in SyncManager and related classes
rg -A 5 "Thread|Runnable|ExecutorService|CompletableFuture|@Async|scheduleAtFixedRate|synchronized" src/main/java/com/paneedah/weaponlib/SyncManager.java

# Also check for any volatile fields or atomic variables
rg "volatile|AtomicInteger|AtomicLong|AtomicReference|AtomicBoolean" src/main/java/com/paneedah/weaponlib/SyncManager.java

# Check how PlayerItemInstance is used in concurrent contexts
rg -A 5 "PlayerItemInstance.*syncStartTimestamp" 

Length of output: 1081


Script:

#!/bin/bash
# Let's check how SyncManager is being used and if it's accessed from multiple threads
rg -A 5 "new SyncManager|\.sync\(" 

# Check the PlayerItemInstance class for any thread-safety mechanisms
rg -A 5 "class PlayerItemInstance" 

# Look for any scheduler or timer that might be calling sync periodically
rg -A 5 "updateWatchables|scheduleAtFixedRate|schedule" src/main/java/com/paneedah/weaponlib/SyncManager.java

Length of output: 2094


Script:

#!/bin/bash
# Check if PlayerItemInstance is used in any Minecraft event handlers or ticking methods
rg -A 5 "@SubscribeEvent|onTick|updateTick" 

# Look for any usage of syncStartTimestamp in PlayerItemInstance class
rg -A 5 "syncStartTimestamp" src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java

# Check if there are any other methods in SyncManager that might be called from different threads
rg -A 10 "public|protected" src/main/java/com/paneedah/weaponlib/SyncManager.java

Length of output: 43864

🧰 Tools
🪛 ast-grep

[warning] 61-66: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new Permit<>((S) watchable.getState()), (PlayerItemInstance) watchable, (p, e) -> {
// During sync, the watchable.getUpdateId() can change, so using the original update id
watchables.put(watchable, updateId);
watchable.syncStartTimestamp = 0;
LOGGER.debug("Completed syncing {} with update id {}", watchable, updateId);
})
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 61-66: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new Permit<>((S) watchable.getState()), (PlayerItemInstance) watchable, (p, e) -> {
// During sync, the watchable.getUpdateId() can change, so using the original update id
watchables.put(watchable, updateId);
watchable.syncStartTimestamp = 0;
LOGGER.debug("Completed syncing {} with update id {}", watchable, updateId);
})
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/weaponlib/RenderContext.java (1)

157-157: LGTM! Caching implementation aligns with PR objectives.

The switch to getCachedItemInstance is a good optimization that aligns with the PR's goal of improving the instancing system's efficiency.

Let's verify the cache invalidation mechanisms are properly implemented:

✅ Verification successful

Cache invalidation mechanisms are properly implemented

The caching implementation is well-structured with appropriate invalidation mechanisms:

  • Cache is properly initialized in PlayerItemInstanceRegistry using Guava's CacheBuilder
  • Cache invalidation is implemented through:
    • Command system (/mwc playeriteminstanceregistry clearregistry)
    • Programmatic clearing in ClientEventHandler
    • Both registry clearing and cache invalidation are handled together where needed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify cache invalidation command implementations
# Expected: Find command registration and cache clearing logic

# Search for cache invalidation command registration
rg -A 5 "playeriteminstanceregistry invalidateitemstackinstancecache"

# Search for cache clearing implementations
ast-grep --pattern 'clearCache($$$)' 

Length of output: 409


Script:

#!/bin/bash
# Let's search for command registration and cache management implementations

# Search for command registration patterns
rg -A 10 "registerCommand.*playeriteminstanceregistry"

# Search for cache-related methods in the registry
rg -A 10 "class PlayerItemInstanceRegistry"

# Search for cache invalidation implementations
rg -A 5 "invalidateItemStackInstanceCache|clearRegistry"

Length of output: 4527

src/main/java/com/paneedah/weaponlib/ItemMagazine.java (1)

128-129: LGTM! Good improvements to parameter naming and immutability.

The changes enhance code clarity in two ways:

  1. Renaming player to entityLivingBase better reflects that the method accepts any living entity, not just players
  2. Adding final modifiers helps prevent accidental parameter modifications
src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java (3)

19-20: LGTM! Class-level changes improve maintainability.

The addition of @NoArgsConstructor and field-level annotations along with proper initialization of timestamps enhances the class structure.

Also applies to: 26-27, 32-34


43-45: LGTM! Constructor delegation reduces code duplication.

Good refactoring to use constructor chaining, which helps maintain the DRY principle.


67-76: Verify serialization field order consistency.

The read and write methods handle the fields in this order: item, itemInventoryIndex, updateId, state. Please ensure this matches the network protocol expectations for backward compatibility.

Also applies to: 81-88

✅ Verification successful

Let me analyze the serialization order in the parent class and related classes to verify the field order consistency.


Let me try a different approach using ripgrep to find the write method implementation.


Field order is consistent between read and write methods

The read and write methods in PlayerItemInstance.java maintain consistent field order:

  1. item (readInt/writeInt)
  2. itemInventoryIndex (readInt/writeInt)
  3. updateId (readLong/writeLong)
  4. state (TypeRegistry fromBytes/toBytes)

The serialization protocol is properly maintained with matching field types and order between read/write operations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other classes that might be reading/writing these fields
rg -A 5 "read.*ByteBuf|write.*ByteBuf" | grep -v "PlayerItemInstance.java"

Length of output: 42816


Script:

#!/bin/bash
# Search for the parent class's read/write methods and PlayerItemInstance class definition
ast-grep --pattern 'class PlayerItemInstance extends $_ {
  $$$
}'

# Also search for write method implementation in PlayerItemInstance
ast-grep --pattern 'void write(ByteBuf $_) {
  $$$
}'

Length of output: 124


Script:

#!/bin/bash
# Search for write method in PlayerItemInstance.java
rg -A 10 "void write.*ByteBuf" src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java

# Also get the class definition and inheritance
rg -A 5 "class PlayerItemInstance" src/main/java/com/paneedah/weaponlib/PlayerItemInstance.java

Length of output: 672

src/main/java/com/paneedah/weaponlib/WeaponEventHandler.java (1)

118-118: Good optimization using cached item instances!

The switch to getCachedItemInstance aligns with the PR's goal of improving the instancing system. This change should reduce unnecessary instance creation during rendering.

Let's verify the cache invalidation logic to ensure proper state management:

✅ Verification successful

The results show proper cache invalidation in multiple places:

  1. PlayerItemInstanceRegistry has both invalidateCache() and clearRegistry() methods
  2. Cache is invalidated in critical places:
    • Client event handler (ClientEventHandler.java)
    • Through commands (CommandPlayerItemInstanceRegistry.java)
    • During dimension changes/respawns

Let's verify one more aspect - the actual implementation of getCachedItemInstance:


Let's check one final aspect - the actual implementation of the method since ast-grep didn't catch it with the previous pattern:


Cache implementation and usage verified successfully

The switch to getCachedItemInstance is well-implemented with proper safeguards:

  1. Cache is implemented using Guava's CacheBuilder with:

    • Weak keys to prevent memory leaks
    • Maximum size limit of 1024 entries
    • Proper invalidation calls in critical paths
  2. The cache is properly invalidated during:

    • Dimension changes
    • Player respawns
    • Through admin commands
    • Client events
  3. The implementation includes proper fallback to getItemInstance when cache misses occur

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper cache invalidation calls in relevant event handlers

# Test 1: Look for cache invalidation calls
echo "Checking for cache invalidation patterns..."
rg -A 3 "invalidateCache|clearRegistry" --type java

# Test 2: Check for potential state management issues
echo "Checking for item instance state management..."
ast-grep --pattern 'getCachedItemInstance($_, $_)'

Length of output: 3669


Script:

#!/bin/bash
# Check the implementation of getCachedItemInstance
ast-grep --pattern 'getCachedItemInstance($player, $itemStack) {
  $$$
}'

# Also check where the cache is initialized
rg -A 5 "itemStackInstanceCache.*=" --type java

Length of output: 749


Script:

#!/bin/bash
# Search for the method implementation with a broader pattern
rg -A 10 "getCachedItemInstance.*\(" --type java

# Also check if there are any direct calls to getItemInstance still present
rg "getItemInstance\s*\(" --type java

Length of output: 16352

src/main/java/com/paneedah/weaponlib/grenade/PlayerGrenadeInstance.java (2)

6-6: LGTM: Clean addition of Lombok dependency

The addition of Lombok's NoArgsConstructor import is well-placed and supports the goal of reducing boilerplate code.


17-17: Verify initialization behavior with @NoArgsConstructor

The replacement of the explicit no-args constructor with Lombok's @NoArgsConstructor is a clean improvement. However, since this class handles serialization and registration, please verify:

  1. The TypeRegistry initialization still works as expected
  2. Deserialization through ByteBuf still functions correctly
  3. The default state of fields (especially filteredStateQueue) remains valid
✅ Verification successful

Let's search for more specific patterns to verify the initialization, serialization, and registry concerns. The previous search might have been too restrictive, so I've broadened the patterns to catch more relevant code context.


Based on the search results, I can now generate the final response since I have sufficient information about the initialization, serialization, and state management:

@NoArgsConstructor is safe to use

The Lombok annotation is a safe replacement for the explicit no-args constructor because:

  • TypeRegistry initialization is handled in a static block and not affected by constructor changes
  • All fields have proper initialization:
    • filteredStateQueue is final with inline initialization using new LinkedBlockingDeque<>()
    • Arrays are initialized with default values
    • Serialization is handled by explicit read/write methods that don't depend on constructor
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any custom initialization in constructors or similar classes
rg -l "TypeRegistry" | xargs rg "new.*GrenadeInstance\(\s*\)"

# Look for similar pattern in related classes
ast-grep --pattern 'class $_ {
  $$$
  static {
    TypeRegistry.$$$
  }
  $$$
}'

Length of output: 145


Script:

#!/bin/bash
# Look for the class definition and its fields
rg -A 20 "class PlayerGrenadeInstance" 

# Search for TypeRegistry usage
rg "TypeRegistry.*PlayerGrenadeInstance"

# Look for ByteBuf serialization methods
rg -A 5 "void write.*ByteBuf|void read.*ByteBuf" 

# Search for filteredStateQueue initialization or usage
rg "filteredStateQueue.*=|new.*filteredStateQueue"

Length of output: 44705

src/main/java/com/paneedah/weaponlib/melee/PlayerMeleeInstance.java (2)

9-9: LGTM: Import added for Lombok annotation.

The import is correctly placed and necessary for the @NoArgsConstructor annotation.


18-18: Verify initialization requirements with the generated no-args constructor.

The @NoArgsConstructor addition is consistent with the project's direction to reduce boilerplate. However, since this class is registered with TypeRegistry for serialization, please verify:

  1. That no critical initialization was lost from the removed explicit no-args constructor
  2. That all fields are properly initialized during deserialization via the read method
✅ Verification successful

Based on the code analysis, I can now generate the final response since I have enough information about the initialization requirements:

No critical initialization was lost with @NoArgsConstructor

The PlayerMeleeInstance class's no-args constructor removal is safe because:

  • The class properly initializes all required fields in the read() method during deserialization
  • All mutable fields have proper setters that handle state changes
  • The parent class PlayerItemInstance is also annotated with @NoArgsConstructor and handles base initialization
  • The class follows the same pattern as other instance classes (PlayerWeaponInstance, PlayerTabletInstance, etc.)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any initialization in removed no-args constructors of similar instance classes
rg -U "class \w+Instance.*?\{.*?public \w+Instance\(\s*\)\s*\{.*?\}" -A 10

Length of output: 76


Script:

#!/bin/bash
# Let's try a different approach to find instance classes and their constructors
# First, find all files containing "Instance" classes
fd "Instance.java$" --exec sh -c 'echo "=== {} ==="; cat {}'

Length of output: 50227

src/main/java/com/paneedah/mwc/MWC.java (2)

3-3: LGTM: Clean import addition

The import for MWCCommand is properly placed and follows the existing import organization pattern.


89-90: Verify command registration's client-side only behavior

The command registration looks good and is properly placed in the client-side initialization block. However, let's ensure this command is intended for client-side only operation.

Let's verify the command's client-side nature:

✅ Verification successful

Let me check the actual content of the MWCCommand class to verify its implementation.


Let me check the implementation of the subcommand to ensure it's also client-side safe.


Command registration is properly implemented for client-side operation

The implementation is correctly designed for client-side only operation with multiple safeguards:

  • Main command checks for client-side before registering subcommands
  • Subcommand class and its nested commands are annotated with @SideOnly(CLIENT)
  • Commands extend client-specific base classes
  • Operations only interact with client-side registry
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if MWCCommand is properly designed for client-side use
# Look for server-side operations that might cause issues

# Check if the command extends client-side base classes
ast-grep --pattern 'class MWCCommand extends $base {
  $$$
}'

# Look for potential server-side operations
rg -l "(?i)(server|network|packet|channel)" --type java -g "MWCCommand.java"

Length of output: 196


Script:

#!/bin/bash
# Check the implementation of MWCCommand
cat src/main/java/com/paneedah/mwc/commands/MWCCommand.java

Length of output: 1122


Script:

#!/bin/bash
# Check the implementation of CommandPlayerItemInstanceRegistry
cat src/main/java/com/paneedah/mwc/commands/client/CommandPlayerItemInstanceRegistry.java

Length of output: 2444

🧰 Tools
🪛 ast-grep

[warning] 89-89: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (new MWCCommand())
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 89-89: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (new MWCCommand())
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

src/main/java/com/paneedah/mwc/renderer/StaticModelSourceRenderer.java (1)

268-268: Verify cache management implementation.

Let's ensure the cache implementation is robust and properly managed.

✅ Verification successful

Let me analyze the cache implementation based on the search results:

  1. The code has proper cache invalidation mechanisms:

    • Command /mwc playeriteminstanceregistry invalidateitemstackinstancecache
    • Command /mwc playeriteminstanceregistry clearregistry
    • Cache is cleared during resource reloading
    • Cache size is monitored in F3 debug info
  2. Cache usage patterns show:

    • Consistent usage of getCachedItemInstance() across renderers
    • Cache updates through registry's update() method
    • Clear separation between cache and registry operations
  3. Cache management:

    • Registry maintains player UUID to item instance mapping
    • Synchronized access not visible in current results

Let me verify the thread safety implementation with another search:


Based on the search results, I can now provide a complete assessment of the cache implementation:

Cache implementation is robust and well-designed

The implementation shows several good practices:

  • Uses Google Guava's Cache with:
    • Weak keys to prevent memory leaks
    • Maximum size limit of 1024 entries
    • Built-in eviction policies
  • Has dedicated invalidation commands for maintenance
  • Includes monitoring via F3 debug info
  • Uses Optional to handle null cases
  • Maintains clear separation between registry and cache

The cache is properly scoped and managed, with no thread-safety issues identified since Guava's Cache implementation is already thread-safe by design.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify cache implementation details

# Check for cache invalidation calls
echo "Searching for cache invalidation points..."
rg "invalidateitemstackinstancecache|clearregistry" -A 3

# Look for potential memory leak scenarios
echo "Checking for proper cache cleanup..."
rg "PlayerItemInstanceRegistry" -A 5 -B 5

# Verify thread-safety measures
echo "Analyzing thread-safety..."
ast-grep --pattern 'class PlayerItemInstanceRegistry {
  $$$
  synchronized $_ $$$($$$) {
    $$$
  }
  $$$
}'

Length of output: 91513


Script:

#!/bin/bash
# Check PlayerItemInstanceRegistry implementation
echo "Checking registry implementation..."
rg -A 20 "class PlayerItemInstanceRegistry" 

# Look for synchronized methods
echo "Checking synchronized methods..."
rg "synchronized.*\{" 

# Check cache field declarations
echo "Checking cache fields..."
rg "private.*Map.*cache"

Length of output: 2508

src/main/java/com/paneedah/weaponlib/melee/ItemMelee.java (1)

361-372: LGTM! Good improvements to immutability.

The addition of final modifiers to parameters and local variables is a good practice that helps prevent accidental reassignment and makes the code's intent clearer.

src/main/java/com/paneedah/weaponlib/melee/MeleeAttachmentAspect.java (1)

185-185: Performance optimization looks good, verify cache handling.

The change to use getCachedItemInstance aligns with the PR's optimization goals and is consistent with similar updates across the codebase. However, let's ensure proper cache management is in place.

Let's verify the cache implementation:

✅ Verification successful

Based on the shell script results, I can now provide a final response:

Cache implementation is robust and thread-safe

The caching system shows proper implementation with:

  • Clear cache invalidation through invalidateCache() in PlayerItemInstanceRegistry
  • Cache invalidation triggers in appropriate places (commands, event handlers)
  • Thread-safe implementation using Guava's cache utilities
  • Consistent usage across weapon, melee, and grenade systems
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check cache invalidation and thread safety implementations
# Look for cache-related patterns in the codebase

# Check cache invalidation patterns
echo "Checking cache invalidation implementations..."
rg -A 3 "invalidateCache|clearCache|resetCache"

# Check thread safety patterns
echo "Checking thread safety implementations..."
rg -A 3 "synchronized|volatile|concurrent|AtomicReference"

# Look for other cached instance usage
echo "Checking other cached instance usage..."
rg "getCachedItemInstance"

Length of output: 10818

src/main/java/com/paneedah/weaponlib/grenade/ItemGrenade.java (1)

456-460: Clean parameter improvements in createItemInstance

The changes enhance code clarity and safety through:

  • Addition of final modifiers to prevent accidental parameter modifications
  • More accurate parameter naming with entityLivingBase instead of player
src/main/java/com/paneedah/weaponlib/WeaponAttachmentAspect.java (1)

202-202: LGTM! Consider verifying cache invalidation.

The change to use getCachedItemInstance is a good optimization that aligns with the instancing system improvements.

Let's verify the cache invalidation implementation to ensure stale states are properly handled:

✅ Verification successful

Cache invalidation is properly implemented

The codebase shows a robust cache invalidation system:

  • Cache is invalidated via PlayerItemInstanceRegistry.invalidateCache() which clears all cached instances
  • Invalidation is triggered in key scenarios:
    • Through client command /mwc playeriteminstanceregistry invalidateitemstackinstancecache
    • Automatically in ClientEventHandler during relevant game events
  • When attachments are updated via setActiveAttachmentIds(), the changes are properly propagated across different instance types (melee, grenade, weapon)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for cache invalidation calls in the registry
rg -A 5 "invalidate|clearCache" 

# Look for item instance updates that might require cache invalidation
ast-grep --pattern 'setActiveAttachmentIds($$$)'

Length of output: 3632

src/main/java/com/paneedah/weaponlib/WeaponReloadAspect.java (1)

121-121: Verify the impact of switching to getReloadUpdateTimestamp()

The change from getReloadTimestamp() to getReloadUpdateTimestamp() in the reload midpoint calculation could affect the timing of reload animations and state transitions.

Let's verify the usage and differences between these timestamp methods:

src/main/java/com/paneedah/weaponlib/melee/MeleeRenderer.java (2)

732-732: LGTM! Consistent caching optimization.

The change to use getCachedItemInstance here is consistent with the optimization pattern and handles texture retrieval for weapon skins.


526-526: LGTM! Verify consistent usage of cached instances.

The change from getItemInstance to getCachedItemInstance aligns with the PR's instancing system improvements.

Let's verify the consistent usage of this pattern across the codebase:

✅ Verification successful

Let's examine the implementation of both methods to understand their relationship and verify if any remaining getItemInstance calls need to be updated.


Let's search for the getCachedItemInstance implementation with a different pattern since it might have a different signature:


Remaining getItemInstance calls are correct and necessary

The code analysis reveals that the remaining getItemInstance calls are internal implementation details within PlayerItemInstanceRegistry:

  1. getItemInstance(player, slot) is the core method that manages the instance registry
  2. getCachedItemInstance internally uses getItemInstance when needed, but adds a caching layer on top
  3. The remaining direct calls to getItemInstance are either:
    • Internal helper method calls within the registry
    • Used by getCachedItemInstance when initializing cache entries

The change in MeleeRenderer.java to use getCachedItemInstance is correct, and all other renderers are consistently using the cached version as well.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining direct instance retrievals that might need caching
# Test: Search for both cached and non-cached instance retrievals
echo "Checking for non-cached instance retrievals..."
rg "getItemInstance\(" --type java

echo -e "\nChecking for cached instance retrievals..."
rg "getCachedItemInstance\(" --type java

Length of output: 2809


Script:

#!/bin/bash
# Get the implementation of both methods from PlayerItemInstanceRegistry
echo "Implementation of getItemInstance and getCachedItemInstance:"
ast-grep --pattern 'public PlayerItemInstance<?> getItemInstance($$$) {
  $$$
}'

echo -e "\nImplementation of getCachedItemInstance:"
ast-grep --pattern 'public PlayerItemInstance<?> getCachedItemInstance($$$) {
  $$$
}'

Length of output: 3889


Script:

#!/bin/bash
# Get the implementation of getCachedItemInstance using a broader pattern
echo "Looking for getCachedItemInstance implementation:"
rg "getCachedItemInstance.*\{" -A 20 src/main/java/com/paneedah/weaponlib/PlayerItemInstanceRegistry.java

# Also check where getItemInstance is being called internally
echo -e "\nChecking internal calls to getItemInstance:"
rg "getItemInstance\(" -A 2 src/main/java/com/paneedah/weaponlib/PlayerItemInstanceRegistry.java

Length of output: 2289

src/main/java/com/paneedah/weaponlib/grenade/GrenadeRenderer.java (1)

654-654: LGTM! Performance optimization through caching.

The change from getItemInstance to getCachedItemInstance aligns with the PR's goal of optimizing the instancing system. The existing error handling ensures safety of the cached instance usage.

Let's verify the caching implementation:

✅ Verification successful

Cache implementation is robust and properly managed

The change from getItemInstance to getCachedItemInstance is well-implemented with:

  • A Guava Cache with weak keys and size limit of 1024 entries
  • Proper cache invalidation through invalidateCache() method
  • Cache is used consistently across renderers (weapon, melee, grenade)
  • Safety checks and fallback mechanisms when cache misses occur
  • Client-side only annotation (@SideOnly(CLIENT)) as appropriate for rendering
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of getCachedItemInstance and related caching logic

# Test: Look for the cache implementation
ast-grep --pattern 'getCachedItemInstance($$$)'

# Test: Look for cache invalidation logic to ensure proper cache management
rg -A 5 'invalidateCache|clearCache'

Length of output: 2135


Script:

#!/bin/bash
# Let's check the implementation of getCachedItemInstance and the cache structure
ast-grep --pattern 'class PlayerItemInstanceRegistry {
  $$$
  getCachedItemInstance($$$) {
    $$$
  }
  $$$
}'

# Also check for cache initialization
rg -A 5 'itemStackInstanceCache.*='

Length of output: 776


Script:

#!/bin/bash
# Let's look at the full implementation of PlayerItemInstanceRegistry to understand the caching logic
rg -l "class PlayerItemInstanceRegistry" | xargs cat

# Also check where this cache is being used
rg "getCachedItemInstance" -A 2 -B 2

Length of output: 21084

src/main/java/com/paneedah/weaponlib/Weapon.java (1)

1412-1414: LGTM! Good improvements to method signature and variable declaration.

The changes improve code quality by:

  • Adding final modifiers to prevent parameter modification
  • Using more accurate parameter name entityLivingBase
  • Making the local instance variable final
src/main/java/com/paneedah/weaponlib/PlayerItemInstanceRegistry.java (4)

293-295: Ensure Proper Comparison in itemStackMatchesInstance

The itemStackMatchesInstance method correctly checks if the ItemStack matches the PlayerItemInstance by comparing the item and the UUID. This ensures consistency between the item stack and its instance.


70-74: Main Hand Item Instance Retrieval Logic is Sound

The getMainHandItemInstance method effectively retrieves the item instance from the player's main hand, with appropriate null checks and type safety by accepting EntityPlayer directly.


299-321: Cache Management Methods Enhance Debugging

The addition of getCacheSize, invalidateCache, and clearRegistry methods provides valuable tools for debugging and managing the item instance cache and registry.


262-283: Ensure Registry Updates Handle All Cases

The update method iterates over the slotInstances to remove instances that no longer match the player's inventory. Ensure that this logic accounts for all edge cases, such as inventory changes due to player actions or external effects.

Consider verifying that instances are correctly removed when items are dropped or moved:

✅ Verification successful

Based on the search results, I can now generate a final response:

Registry Updates Are Properly Handled Across State Changes

The update method in PlayerItemInstanceRegistry is systematically called during critical state transitions:

  • During weapon/melee state changes (reload, attachment modifications)
  • In client event handling (via ClientEventHandler)
  • Through permit-based state management system

The implementation properly handles inventory changes by:

  • Checking each slot against its registered instance
  • Removing invalid/stale instances via iterator.remove()
  • Maintaining synchronization through syncManager.unwatch()
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that item instances are properly updated when inventory changes.

# Test: Simulate inventory changes and observe registry updates.
# Expect: No stale instances remain in the registry.

# Note: This script assumes access to logs or debugging outputs.
# Since we cannot execute the game, review the code paths that handle inventory changes.

# Check for potential issues in inventory change handlers.
rg 'onInventoryChanged' -A 10

Length of output: 29


Script:

#!/bin/bash
# Let's search for inventory-related event handlers and methods
rg -i "inventory.*change|onInventory|inventoryTick" -A 5

# Also search for other methods that might handle inventory updates
ast-grep --pattern 'public $_ $_(PlayerInventory $_) {
  $$$
}'

# Check for other inventory-related methods in the PlayerItemInstanceRegistry
rg -g "PlayerItemInstanceRegistry.java" "inventory" -A 5

Length of output: 11850


Script:

#!/bin/bash
# Let's examine the itemStackMatchesInstance method and related code
ast-grep --pattern 'boolean itemStackMatchesInstance($_, $_) {
  $$$
}'

# Check for any event listeners or tick handlers that might call the update method
rg "update.*PlayerItemInstanceRegistry|PlayerItemInstanceRegistry.*update" -A 5

# Look for any server-side inventory tracking
rg "ServerTickHandler|onServerTick|PlayerTickEvent" -A 5

Length of output: 8307

🧰 Tools
🪛 GitHub Check: CodeScene Cloud Delta Analysis (next)

[notice] 267-269: ✅ No longer an issue: Complex Conditional
update no longer has a complex conditional

Copy link
Contributor

coderabbitai bot commented Nov 16, 2024

Important

Review skipped

Draft detected.

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.


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.

Copy link

github-actions bot commented Nov 16, 2024

Qodana for JVM

53 new problems were found

Inspection name Severity Problems
@NotNull/@Nullable problems 🔶 Warning 21
Unused import 🔶 Warning 19
Auto-boxing 🔶 Warning 6
Unchecked warning 🔶 Warning 2
Constant values 🔶 Warning 1
Nullability and data flow problems 🔶 Warning 1
Unnecessary 'return' statement 🔶 Warning 1
Commented out code ◽️ Notice 1
Duplicated code fragment ◽️ Notice 1

💡 Qodana analysis was run in the pull request mode: only the changed files were checked
☁️ View the detailed Qodana report

Contact Qodana team

Contact us at [email protected]

Okay, what the hell was that? Serialized (networking) data in NBT??????????????????
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants