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

[PLA-1826] Change beam events broadcast #73

Merged
merged 10 commits into from
Jun 20, 2024
Merged

[PLA-1826] Change beam events broadcast #73

merged 10 commits into from
Jun 20, 2024

Conversation

leonardocustodio
Copy link
Contributor

@leonardocustodio leonardocustodio commented Jun 6, 2024

PR Type

enhancement, dependencies, tests


Description

  • Removed the PHP CS Fixer configuration file.
  • Replaced event broadcasting with safeBroadcast method in multiple files.
  • Modified constructors and updated broadcast data structures in event classes.
  • Adjusted conditional checks and spacing for consistency across various files.
  • Reordered traits for consistency in multiple GraphQL mutation and type files.
  • Updated dependencies to replace php-cs-fixer with laravel/pint.

Changes walkthrough 📝

Relevant files
Dependencies
1 files
.php-cs-fixer.php
Remove PHP CS Fixer configuration file                                     

.php-cs-fixer.php

  • Removed the PHP CS Fixer configuration file.
+0/-165 
Enhancement
14 files
BatchProcess.php
Update event broadcasting and conditional spacing               

src/Commands/BatchProcess.php

  • Replaced event broadcasting with safeBroadcast method.
  • Adjusted conditional spacing for consistency.
  • +15/-8   
    BeamBatchTransactionCreated.php
    Update BeamBatchTransactionCreated event structure             

    src/Events/BeamBatchTransactionCreated.php

  • Modified constructor to accept mixed event data.
  • Updated broadcast data structure.
  • +5/-4     
    BeamClaimPending.php
    Update BeamClaimPending event structure                                   

    src/Events/BeamClaimPending.php

  • Modified constructor to accept mixed event data.
  • Updated broadcast data structure.
  • +10/-9   
    BeamCreated.php
    Update BeamCreated event structure                                             

    src/Events/BeamCreated.php

  • Modified constructor to accept mixed event data.
  • Updated broadcast data structure.
  • +2/-1     
    CreateBeamClaimsCompleted.php
    Update CreateBeamClaimsCompleted event structure                 

    src/Events/CreateBeamClaimsCompleted.php

  • Modified constructor to accept mixed event data.
  • Updated broadcast data structure.
  • +4/-4     
    TokensAdded.php
    Update TokensAdded event structure                                             

    src/Events/TokensAdded.php

  • Modified constructor to accept mixed event data.
  • Updated broadcast data structure.
  • +6/-3     
    AddTokensMutation.php
    Adjust conditional checks in AddTokensMutation                     

    src/GraphQL/Mutations/AddTokensMutation.php

    • Adjusted conditional checks for consistency.
    +3/-3     
    ClaimBeamMutation.php
    Reorder traits in ClaimBeamMutation                                           

    src/GraphQL/Mutations/ClaimBeamMutation.php

    • Reordered traits for consistency.
    +1/-1     
    CreateBeamMutation.php
    Adjust conditional checks in CreateBeamMutation                   

    src/GraphQL/Mutations/CreateBeamMutation.php

    • Adjusted conditional checks for consistency.
    +4/-4     
    UpdateBeamMutation.php
    Adjust conditional checks in UpdateBeamMutation                   

    src/GraphQL/Mutations/UpdateBeamMutation.php

    • Adjusted conditional checks for consistency.
    +3/-3     
    BeamClaimType.php
    Reorder traits in BeamClaimType                                                   

    src/GraphQL/Types/BeamClaimType.php

    • Reordered traits for consistency.
    +1/-1     
    BeamType.php
    Adjust conditional checks in BeamType                                       

    src/GraphQL/Types/BeamType.php

    • Adjusted conditional checks for consistency.
    +2/-2     
    IntegerRangeStringType.php
    Reorder traits and adjust conditionals in IntegerRangeStringType

    src/GraphQL/Types/Input/IntegerRangeStringType.php

  • Reordered traits for consistency.
  • Adjusted conditional checks for consistency.
  • +4/-4     
    ClaimBeam.php
    Adjust exception handling in ClaimBeam job                             

    src/Jobs/ClaimBeam.php

    • Adjusted exception handling for consistency.
    +2/-2     

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @leonardocustodio leonardocustodio self-assigned this Jun 6, 2024
    @github-actions github-actions bot added enhancement New feature or request dependencies Pull requests that update a dependency file tests labels Jun 6, 2024
    @leonardocustodio leonardocustodio requested review from v16Studios and enjinabner and removed request for v16Studios June 6, 2024 17:59
    Copy link

    github-actions bot commented Jun 6, 2024

    PR Review 🔍

    ⏱️ Estimated effort to review [1-5]

    4, because the PR involves multiple files and significant changes including method replacements, conditional checks, and broadcasting event modifications. The complexity and breadth of changes require careful review to ensure functionality and consistency across the application.

    🧪 Relevant tests

    No

    ⚡ Possible issues

    Possible Bug: The replacement of event() with safeBroadcast() might not directly map due to the difference in their signatures and expected parameters. This could lead to issues if not properly handled.

    Code Consistency: The use of spacing in conditional checks (e.g., if (! $batches->isEmpty())) has been made consistent, but this style change should be confirmed as the project's standard.

    🔒 Security concerns

    No

    Code feedback:
    relevant filesrc/Commands/BatchProcess.php
    suggestion      

    Consider verifying the success of the safeBroadcast() method calls. Since broadcasting events is crucial for the application's functionality, ensuring that these methods do not fail silently could improve reliability. [important]

    relevant lineBeamClaimInProgress::safeBroadcast(event: $claim->toArray());

    relevant filesrc/Events/BeamBatchTransactionCreated.php
    suggestion      

    Ensure that the transaction model is properly checked for null before attempting to access its id. This prevents potential null reference exceptions. [important]

    relevant line'transactionId' => $transaction?->id,

    relevant filesrc/GraphQL/Mutations/AddTokensMutation.php
    suggestion      

    Refactor the repeated logic for checking BeamType in conditional statements to a separate method or use a strategy pattern for better code reuse and readability. [medium]

    relevant lineRule::prohibitedIf(BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute))) == BeamType::TRANSFER_TOKEN),

    relevant filesrc/Jobs/ClaimBeam.php
    suggestion      

    Implement a retry mechanism or a more sophisticated error handling strategy for the LockTimeoutException to enhance the robustness of the job processing. [medium]

    relevant line} catch (LockTimeoutException) {

    Copy link

    github-actions bot commented Jun 6, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible bug
    Correct the logical operator in the conditional check to properly validate token supply limits

    The comparison in the conditional statement should use the correct logical operator to
    ensure that the validation correctly checks if the max_token_supply from the collection is
    greater than or equal to the value. The current implementation might lead to incorrect
    validation behavior.

    src/Rules/MaxTokenSupply.php [56]

    -if (! $collection->max_token_supply >= $value) {
    +if ($collection->max_token_supply < $value) {
         $fail($this->maxTokenSupplyMessage)
             ->translate([
                 'limit' => $this->limit,
     
    Suggestion importance[1-10]: 10

    Why: The suggestion corrects a potential logical error in the validation check, ensuring that the comparison correctly validates if the max_token_supply is greater than or equal to the value. This is crucial for the correct functioning of the validation rule.

    10
    Add null checks to prevent potential null pointer exceptions

    Consider checking if $transaction is not null before using its id property to avoid
    potential null pointer exceptions when updating the BeamBatch.

    src/Commands/BatchProcess.php [215]

    -BeamBatch::where('id', $batchId)->update(['transaction_id' => $transaction->id]);
    +if ($transaction) {
    +    BeamBatch::where('id', $batchId)->update(['transaction_id' => $transaction->id]);
    +}
     
    Suggestion importance[1-10]: 9

    Why: Adding a null check before using the id property of $transaction is a good practice to prevent potential null pointer exceptions, which can cause runtime errors. This suggestion addresses a possible bug and improves code robustness.

    9
    Best practice
    Check for non-empty token IDs before processing to avoid handling invalid data

    When checking if token IDs exist, it's safer to ensure that $tokenId is not empty before
    pushing it to the $ids array. This prevents potential issues with empty or invalid token
    IDs being processed.

    src/Rules/TokenUploadExistInCollection.php [36]

    -if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) {
    +$tokenId = trim($line);
    +if (!empty($tokenId) && ! $this->tokenIdExists($ids->all(), $tokenId)) {
         $ids->push($tokenId);
         yield $tokenId;
     
    Suggestion importance[1-10]: 9

    Why: Ensuring that token IDs are not empty before processing them prevents potential issues with invalid data, enhancing the reliability and correctness of the code.

    9
    Add a null coalescing check to prevent accessing a null property

    It is recommended to check for the existence of the max_token_supply attribute in the
    collection object before attempting to access it. This prevents potential errors when the
    attribute is not set.

    src/Rules/MaxTokenSupply.php [53]

    -&& ! is_null($this->limit = $collection->max_token_supply)
    +&& ! is_null($this->limit = $collection->max_token_supply ?? null)
     
    Suggestion importance[1-10]: 8

    Why: Adding a null coalescing check is a good practice to prevent potential errors when accessing properties that might not be set. This enhances the robustness of the code.

    8
    Ensure consistency in event broadcasting methods across the application

    Replace the usage of safeBroadcast with the original event function to maintain
    consistency with the rest of the event broadcasting in the application, unless there is a
    specific requirement to use safeBroadcast. If safeBroadcast is a new standard, consider
    refactoring other parts of the application to use it as well.

    src/Commands/BatchProcess.php [113]

    -BeamClaimInProgress::safeBroadcast(event: $claim->toArray());
    +event(new BeamClaimInProgress($claim->toArray()));
     
    Suggestion importance[1-10]: 7

    Why: The suggestion to replace safeBroadcast with the original event function is valid for maintaining consistency. However, if safeBroadcast is a new standard, this change might not be necessary. The suggestion is contextually accurate but not crucial.

    7
    Cast the value to integer to ensure consistent data types for comparison

    Ensure that the value assigned to $value is always an integer by explicitly casting it.
    This is important because the subsequent comparison uses bccomp which expects string
    arguments, and ensuring the type can prevent subtle bugs.

    src/Rules/MinBigIntIntegerRange.php [17]

    -$value = $range === false ? $value : $range[0];
    +$value = $range === false ? (int) $value : (int) $range[0];
     
    Suggestion importance[1-10]: 7

    Why: Explicitly casting the value to an integer ensures consistent data types for comparison, which can prevent subtle bugs. However, since bccomp expects string arguments, this suggestion might not be entirely necessary.

    7
    Enhancement
    Implement a retry limit to prevent excessive retries

    Add a retry limit to prevent potential infinite loops or excessive retries when a lock
    cannot be obtained.

    src/Jobs/ClaimBeam.php [66-67]

    -Log::info('ClaimBeamJob: Cannot obtain lock, retrying', $data);
    -$this->release(1);
    +static $retryCount = 0;
    +$retryLimit = 5;
    +if ($retryCount < $retryLimit) {
    +    Log::info('ClaimBeamJob: Cannot obtain lock, retrying', $data);
    +    $this->release(1);
    +    $retryCount++;
    +} else {
    +    Log::error('ClaimBeamJob: Retry limit reached, aborting', $data);
    +    throw new Exception("Retry limit reached");
    +}
     
    Suggestion importance[1-10]: 9

    Why: Implementing a retry limit is crucial to prevent potential infinite loops or excessive retries, which could lead to resource exhaustion and system instability.

    9
    Validate configuration value to ensure it's a positive integer

    Ensure that the $days variable is not only non-null but also a positive integer before
    proceeding with the query.

    src/Models/Laravel/BeamClaim.php [179]

    -if (! is_null($days = config('enjin-platform-beam.prune_expired_claims'))) {
    +$days = config('enjin-platform-beam.prune_expired_claims');
    +if (is_int($days) && $days > 0) {
         $query = static::whereHas(
             'beam',
             fn ($query) => $query->where('end', '<', now()->addDays($days))
    +} else {
    +    throw new InvalidArgumentException("Expected positive integer for days, received: {$days}");
     }
     
    Suggestion importance[1-10]: 8

    Why: Validating the configuration value to ensure it is a positive integer enhances the robustness of the code and prevents potential runtime errors due to invalid configuration values.

    8
    Add type checking to enhance error handling and debugging

    Add explicit type checking for the $value parameter to ensure it is a string before
    proceeding with validation.

    src/GraphQL/Types/Input/IntegerRangeStringType.php [43-44]

    -if (! is_string($value) || ! $this->isValid($value)) {
    +if (! is_string($value)) {
    +    throw new TypeError("Expected a string, received " . gettype($value));
    +}
    +if (! $this->isValid($value)) {
         throw new Error(__('enjin-platform::error.cannot_represent_integer_range', ['value' => Utils::printSafeJson($value)]));
     }
     
    Suggestion importance[1-10]: 7

    Why: Adding explicit type checking enhances error handling and debugging, making the code more robust. However, it is not addressing a critical issue.

    7
    Possible issue
    Add error handling for file operations to enhance robustness

    Consider adding error handling for the file opening operation. This can prevent issues
    when the file does not exist or cannot be opened due to permissions, enhancing the
    robustness of the code.

    src/Rules/TokenUploadNotExistInCollection.php [29]

     $handle = fopen($value->getPathname(), 'r');
    +if (!$handle) {
    +    throw new \Exception("Failed to open file: " . $value->getPathname());
    +}
     
    Suggestion importance[1-10]: 9

    Why: Adding error handling for file operations is crucial for robustness and preventing runtime errors, especially when dealing with file I/O operations.

    9
    Maintainability
    Enforce type safety for the transaction parameter in the event constructor

    Ensure that the transaction parameter in the constructor is always an instance of Model or
    null. This change requires updating all places where BeamBatchTransactionCreated is
    instantiated to pass a Model or null.

    src/Events/BeamBatchTransactionCreated.php [15]

    -public function __construct(mixed $event, ?Model $transaction, ?array $extra)
    +public function __construct(mixed $event, Model $transaction = null, ?array $extra = [])
     
    Suggestion importance[1-10]: 8

    Why: Ensuring that the transaction parameter is always an instance of Model or null enhances type safety and maintainability. This change is beneficial but requires updating all instantiation points, making it a significant but not critical improvement.

    8
    Improve readability and debuggability by separating variable assignment from the condition

    Replace the usage of trim($line) directly in the condition with a separate variable
    assignment before the condition. This enhances readability and debugging by separating the
    data processing step from the conditional logic.

    src/Rules/TokenUploadNotExistInCollection.php [31]

    -if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) {
    +$tokenId = trim($line);
    +if (! $this->tokenIdExists($ids->all(), $tokenId)) {
         $ids->push($tokenId);
         yield $tokenId;
     }
     
    Suggestion importance[1-10]: 7

    Why: This suggestion improves readability and maintainability by separating the variable assignment from the condition. However, it does not address any critical issues or bugs.

    7
    Refactor lambda function for clarity in conditional checks

    Refactor the lambda function used in the filter method to enhance clarity. Instead of
    using an inline comparison, define the condition more clearly.

    src/Rules/TokenUploadNotExistInCollection.php [40]

    -$integers = $tokenIds->filter(fn ($val) => $this->integerRange($val) === false)->all();
    +$integers = $tokenIds->filter(fn ($val) => !$this->integerRange($val))->all();
     
    Suggestion importance[1-10]: 6

    Why: This suggestion improves code clarity by simplifying the lambda function. However, it is a minor enhancement and does not address any critical issues.

    6
    Improve code consistency by adjusting whitespace

    Consider adding a space after the negation operator for consistency with the rest of the
    codebase.

    src/GraphQL/Types/BeamType.php [70]

    -! $beam->hasFlag(BeamFlag::PAUSED)
    +!$beam->hasFlag(BeamFlag::PAUSED)
     
    Suggestion importance[1-10]: 3

    Why: While the suggestion improves code consistency, it is a minor stylistic change and does not impact functionality or performance.

    3
    Performance
    Improve the efficiency and readability of type comparisons

    Refactor the conditional checks for $type against BeamType::TRANSFER_TOKEN to use a direct
    comparison instead of calling BeamType::getEnumCase, which might be more efficient and
    readable.

    src/Commands/BatchProcess.php [154]

    -if ($type == BeamType::TRANSFER_TOKEN) {
    +if ($type === BeamType::TRANSFER_TOKEN) {
         $params[$collectionId]['recipients'][] = [
             'accountId' => $claim->wallet_public_key,
             'params' => $this->substrate->getTransferParams([
                 'to' => $claim->wallet_public_key,
                 'amount' => $claim->amount,
             ]),
         ];
     }
     
    Suggestion importance[1-10]: 6

    Why: The suggestion to use a direct comparison (===) instead of calling BeamType::getEnumCase is valid for improving efficiency and readability. However, the performance gain is likely minimal, making this a minor improvement.

    6

    @leonardocustodio leonardocustodio marked this pull request as draft June 6, 2024 18:04
    @leonardocustodio leonardocustodio marked this pull request as ready for review June 6, 2024 21:36
    Copy link
    Contributor

    @enjinabner enjinabner left a comment

    Choose a reason for hiding this comment

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

    I think we need to do similar for multi-tenants to update the event test part

    Copy link
    Contributor

    @enjinabner enjinabner left a comment

    Choose a reason for hiding this comment

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

    clarification

    Copy link
    Contributor

    @enjinabner enjinabner left a comment

    Choose a reason for hiding this comment

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

    improvement

    src/Events/BeamBatchTransactionCreated.php Outdated Show resolved Hide resolved
    src/Events/CreateBeamClaimsCompleted.php Outdated Show resolved Hide resolved
    src/Events/TokensAdded.php Outdated Show resolved Hide resolved
    @leonardocustodio leonardocustodio merged commit 6af099f into master Jun 20, 2024
    5 checks passed
    @leonardocustodio leonardocustodio deleted the PLA-1826 branch June 20, 2024 09:53
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    dependencies Pull requests that update a dependency file enhancement New feature or request Review effort [1-5]: 4 tests
    Development

    Successfully merging this pull request may close these issues.

    2 participants