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

Preserve queue job items and cleanup after some time #472

Merged
merged 18 commits into from
Nov 29, 2023

Conversation

srtfisher
Copy link
Member

@srtfisher srtfisher commented Nov 16, 2023

Keep processed and failed jobs around for review after they are out of the system. After some time, come back and delete them using the application scheduler.

Also breaks out the queue model to Queue_Record to make it less confusing.

Summary by CodeRabbit

  • New Features

    • Introduced a search bar in the Hero component for enhanced user navigation.
    • Implemented a new Search component within the application for improved result fetching and display.
  • Style

    • Added custom styles for the new search bar to align with the application's design language.
  • Documentation

    • Updated documentation to reflect the addition of the search functionality and its usage within the app.

@srtfisher srtfisher changed the base branch from 0.12.x to queue-ui November 16, 2023 20:48
Copy link

coderabbitai bot commented Nov 16, 2023

Important

Auto Review Skipped

Auto reviews are disabled on base/target branches other than the default branch. Please add the base/target branch pattern to the list of additional branches to be reviewed in the settings.

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.

Walkthrough

The changes reflect a comprehensive update to a PHP application's queue system, enhancing queue management, job dispatching, and scheduling. New features include batch size configuration, concurrent batch limits, queue item retention settings, and an admin interface for queue management. The application's service provider bindings and core aliases have been updated, and new methods and properties have been added across various classes to improve queue job handling, error logging, and event management. PHP 8 features like constructor property promotion and enums are utilized, indicating a modernization of the codebase.

Changes

File Path Change Summary
config/queue.php Updated queue configuration with new settings for batch sizes, concurrent batches, and queue item retention. Added queue admin interface option.
src/mantle/.../class-app-service-provider.php
src/mantle/.../class-application.php
Changed service binding for scheduler and added new aliases for queue and scheduler services.
src/mantle/contracts/queue/...
src/mantle/database/model/...
src/mantle/database/query/...
src/mantle/queue/...
Updated method signatures and return types, added new methods, and introduced type declarations across various classes and interfaces.
src/mantle/queue/console/...
src/mantle/queue/events/...
src/mantle/queue/providers/wordpress/admin/...
src/mantle/queue/providers/wordpress/...
Added new classes for queue management, event handling, and admin interface functionality.
src/mantle/queue/trait-dispatchable.php
src/mantle/queue/trait-queueable.php
Introduced type declarations for properties and parameters in traits.
src/mantle/scheduling/... Explicitly typed properties and updated method signatures in the scheduling classes.
src/mantle/support/... Minor changes to method signatures in the Collection class.
src/mantle/testing/concerns/... Added new methods, updated existing methods with new serialization logic, and included additional service providers in the application configuration.
tests/database/query/...
tests/queue/providers/...
tests/queue/...
Introduced new test methods, classes, and updated existing tests to accommodate the new queue system changes. Skipped tests for PHP versions less than 8.1.

Note: The ellipsis (...) in the file paths indicates that the path has been shortened to group similar changes and save space.


Tips

Chat with CodeRabbit Bot (@coderabbitai)

  • If you reply to a review comment from CodeRabbit, the bot will automatically respond.
  • To engage with CodeRabbit bot directly around the specific lines of code in the PR, mention @coderabbitai in your review comment
  • Note: Review comments are made on code diffs or files, not on the PR overview.
  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Note: For conversation with the bot, please use the review comments on code diffs or files.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

@srtfisher srtfisher mentioned this pull request Nov 16, 2023
4 tasks
Comment on lines +133 to 137
* @param class-string $job Job class to run.
* @param array $arguments Arguments for the command.
* @return Event
*
* @throws RuntimeException Thrown on missing command.
Copy link

Choose a reason for hiding this comment

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

Similar to the command method, the job method has been updated to include a type declaration for the $job parameter. The comment on line 137 has a typo and should be corrected from "Thrown invalid command class." to "Thrown if an invalid job class is passed." to accurately reflect the exception being thrown.

- * @throws RuntimeException Thrown invalid command class..
+ * @throws RuntimeException Thrown if an invalid job class is passed.

Commitable suggestion

[!IMPORTANT]
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
* @param class-string $job Job class to run.
* @param array $arguments Arguments for the command.
* @return Event
*
* @throws RuntimeException Thrown on missing command.
* @param class-string $job Job class to run.
* @param array $arguments Arguments for the command.
* @return Event
*
* @throws RuntimeException Thrown if an invalid job class is passed.

Comment on lines +1 to +48
<?php
/**
* Cleanup_Jobs_Commands class file.
*
* @package Mantle
*/

namespace Mantle\Queue\Console;

use Mantle\Console\Command;
use Mantle\Contracts\Container;
use Mantle\Queue\Events\Job_Processed;
use Mantle\Queue\Events\Job_Processing;
use Mantle\Queue\Events\Run_Complete;
use Mantle\Queue\Events\Run_Start;
use Mantle\Queue\Providers\WordPress\Post_Status;
use Mantle\Queue\Providers\WordPress\Queue_Record;

/**
* Queue Cleanup Command
*/
class Cleanup_Jobs_Command extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:cleanup';
/**
* Command Description.
*
* @var string
*/
protected $description = 'Cleanup old queue jobs.';

/**
* Command action.
*/
public function handle() {
Queue_Record::query()
->whereStatus( [ Post_Status::FAILED->value, Post_Status::COMPLETED->value ] )
->olderThan( now()->subSeconds( (int) $this->container['config']->get( 'queue.delete_after', 60 ) ) )
->take( -1 )
->each_by_id(
fn ( Queue_Record $record ) => $record->delete( true ),
100,
);
}
Copy link

Choose a reason for hiding this comment

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

The class Cleanup_Jobs_Command is well-structured and follows good object-oriented design principles. It extends the base Command class and defines properties and a method that are clear in their purpose. The handle method uses a fluent interface to build a query, which is a common and readable way to interact with models in modern PHP frameworks.

However, there are a few points to consider:

  • The use of PHP 8's enums (Post_Status::FAILED->value, Post_Status::COMPLETED->value) is a good practice for code clarity and maintainability. Ensure that the rest of the codebase is compatible with PHP 8 features if they are being used here.
  • The olderThan method seems to be a custom addition to the query builder. Ensure that this method is properly defined and tested in the Queue_Record model or query builder class.
  • The take(-1) method call is unusual. Typically, take is used to limit the number of records returned. If -1 is intended to indicate "all records," this should be clearly documented, as it's not a standard convention. If it's a mistake, it should be corrected.
  • The lambda function fn (Queue_Record $record) => $record->delete(true) within each_by_id is concise and takes advantage of PHP 8's arrow functions. Ensure that the delete method on Queue_Record accepts a boolean parameter and that its behavior is well-documented, especially what passing true signifies.
  • There is no error handling in the handle method. Consider what should happen if the deletion fails for one or more Queue_Record instances. Should the command fail entirely, log an error, or continue with the next record? This depends on the desired behavior and robustness of the command.
  • The command retrieves the delete_after configuration value. Ensure that this configuration option is documented and validated elsewhere in the codebase.

Here's a potential update to the take method if -1 is not intended:

- ->take(-1)
+ ->take($this->container['config']->get('queue.cleanup_batch_size', 100))

This change assumes that there's a configuration setting named queue.cleanup_batch_size that controls how many records should be processed at a time.


Commitable suggestion

[!IMPORTANT]
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
<?php
/**
* Cleanup_Jobs_Commands class file.
*
* @package Mantle
*/
namespace Mantle\Queue\Console;
use Mantle\Console\Command;
use Mantle\Contracts\Container;
use Mantle\Queue\Events\Job_Processed;
use Mantle\Queue\Events\Job_Processing;
use Mantle\Queue\Events\Run_Complete;
use Mantle\Queue\Events\Run_Start;
use Mantle\Queue\Providers\WordPress\Post_Status;
use Mantle\Queue\Providers\WordPress\Queue_Record;
/**
* Queue Cleanup Command
*/
class Cleanup_Jobs_Command extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:cleanup';
/**
* Command Description.
*
* @var string
*/
protected $description = 'Cleanup old queue jobs.';
/**
* Command action.
*/
public function handle() {
Queue_Record::query()
->whereStatus( [ Post_Status::FAILED->value, Post_Status::COMPLETED->value ] )
->olderThan( now()->subSeconds( (int) $this->container['config']->get( 'queue.delete_after', 60 ) ) )
->take( -1 )
->each_by_id(
fn ( Queue_Record $record ) => $record->delete( true ),
100,
);
}
/**
* Command action.
*/
public function handle() {
Queue_Record::query()
->whereStatus( [ Post_Status::FAILED->value, Post_Status::COMPLETED->value ] )
->olderThan( now()->subSeconds( (int) $this->container['config']->get( 'queue.delete_after', 60 ) ) )
->take($this->container['config']->get('queue.cleanup_batch_size', 100))
->each_by_id(
fn ( Queue_Record $record ) => $record->delete( true ),
100,
);
}

Base automatically changed from queue-ui to queue-performance November 29, 2023 16:54
@srtfisher srtfisher merged commit 480ece0 into queue-performance Nov 29, 2023
15 checks passed
@srtfisher srtfisher deleted the queue-cleanup branch November 29, 2023 17:20
srtfisher added a commit that referenced this pull request Dec 1, 2023
* Slight refactor for readability

* Refactor to queue model

* Use the query builder internally

* WIP

* Add phpstan typings

* Continued work

* Starting out on count()

* Adding query builder count() method

* Todo for tomorrow

* Set the meta when creating the job

* Improving the logic

* Wrapping up until tmw

* Continued work

* Use the date query builder to get the proper queue items

* Adjust cron logic to properly scale up to meet demand of the queue

* Adding tests for cron queue

* Linting fixes

* Wrapping up fixes for queue

* Raise memory limit, skip queue tests on 8.0

* Prevent queue service provider on 8.1

* Remove bogus version

* Fixing tests

* Remove bogus return

* Add a log of queue job events

* Filling in the queue log

* Adding a database collection and passing along the found_rows to the collection

* Allow the value to be passed

* Queue UI (#458)

* Continued work on queue UI=

* Wrapping up the core of the queue UI

* Working table for queue UI

* Adding counts to the queue

* Switch to use wp_count_posts for performance

* Style the row table

* Adding single view for queue job

* Adding queue UI with fixes for retrying

* Preserve queue job items and cleanup after some time (#472)

* Continued work on queue UI=

* Wrapping up the core of the queue UI

* Working table for queue UI

* Adding counts to the queue

* Switch to use wp_count_posts for performance

* Style the row table

* Adding single view for queue job

* Adding queue UI with fixes for retrying

* Serialize enums when asserting against them

* Keep queue job around after it is complete for logging

* Fixing tests and adjusting comment

* Fixing linting

* Stubbing the cleanup command

* Cleanup the processed/failed jobs after some time

* Fixing phpcs issue

* Remove checks for <8.1 now that were on PHP 8.1+ always

* [1.x] Allow queue jobs to be run in-admin, allow delays for closure jobs (#481)

* Add support for displaying completed queue job status

* Allow a closure job to be delayed

* Allow queue jobs to be run in-admin, allow closure jobs to be delayed

* Add a back link on the queue job page

* Cleanup running jobs with the cleanup command

* Remove the superfluous take()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant