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

Trunk enhancements branch #190

Closed
wants to merge 75 commits into from
Closed

Trunk enhancements branch #190

wants to merge 75 commits into from

Conversation

xepozz
Copy link
Member

@xepozz xepozz commented Jan 14, 2024

Includes:

Differences:

  • Queue messages dispatches through Psr\EventDispatcherInterface
  • SynchronousAdapter triggers on both console and web request end events instead of __destruct() method
  • No more PushDispatcher, ConsomeDispatcher, FailureDispatcher and tens of related classes
  • Eliminated HandlerEnvelope

How to handle messages now:

  1. Create app/config/common/queue.php file
  2. Write the following:
    <?php
    
    declare(strict_types=1);
    
    use App\Queue\HelloMessage;
    use App\Queue\HelloMessageHandler;
    use Yiisoft\Queue\Message\EnvelopeInterface;
    use Yiisoft\Queue\Message\Message;
    
    /** @var array $params */
    
    return [
        HelloMessage::class => [
            fn(HelloMessage $message, HelloMessageHandler $handler) => $handler->handle($message),
        ],
        Message::class => [
            fn(Message $message) => $message instanceof EnvelopeInterface ? $message->getMessage() : $message,
        ],
    ];
  3. The keys are Messages to listen. Each message must implement \Yiisoft\Queue\Message\MessageInterface. \Yiisoft\Queue\Message\MessageTrait may help with it
  4. Values are callables, or simply, handlers, like the yiisoft/event-dispatcher ones

There are HelloeMessage itself:

<?php

declare(strict_types=1);

namespace App\Queue;

use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\Message\MessageTrait;

class HelloMessage implements MessageInterface
{
    use MessageTrait;

    public function __construct(
        private mixed $message
    ) {
        $this->data = $message;
    }
}

And it's handler:

<?php

declare(strict_types=1);

namespace App\Queue;

use Yiisoft\Aliases\Aliases;
use Yiisoft\Queue\Message\MessageHandlerInterface;
use Yiisoft\Queue\Message\MessageInterface;

class HelloMessageHandler implements MessageHandlerInterface
{
    public function __construct(private Aliases $aliases)
    {
    }

    public function handle(MessageInterface $message): void
    {
        file_put_contents(
            $this->aliases->get('@runtime/hello-queue.log'),
            json_encode($message->getData()) . PHP_EOL,
            FILE_APPEND
        );
    }
}

Now you can use the queue as a regular service in any services or controllers:

<?php

declare(strict_types=1);

namespace App\User\Controller;

use App\Queue\HelloMessage;
use App\Queue\PassMiddleware;
use HttpSoft\Response\TextResponse;
use Yiisoft\Queue\Middleware\MessageHandlerInterface;
use Yiisoft\Queue\Middleware\MiddlewareInterface;
use Yiisoft\Queue\Middleware\Request;
use Yiisoft\Queue\QueueInterface;

class TestController
{
    public function index(QueueInterface $queue): TextResponse 
    {
        $queue->push(
            new HelloMessage('Hello, World!'), // the message gonna be written in the file in the HelloMessageHandler
            new class () implements MiddlewareInterface {
                public function process(Request $request, MessageHandlerInterface $handler): Request
                {
                    return $handler->handle($request); // just to be sure all middlewares still work
                }
            }
        );
        return new TextResponse('Hello, World!');
    }
}

After a \Yiisoft\Yii\Http\Event\AfterRequest event is thrown application event dispatcher can trigger SynchronousAdapter::run() and it process all in-memory messages.

SynchronousAdapter does double un- and serialization to apply all envelopes to the final message. So SynchronousAdapter stores serialized with \Yiisoft\Queue\Message\MessageSerializerInterface, currently it's \Yiisoft\Queue\Message\JsonMessageSerializer.
When it starts to handles the stored messages it decodes the ones with the same \Yiisoft\Queue\Message\MessageSerializerInterface and applies all envelopes before it goes to the final queue message handler.

xepozz and others added 30 commits December 25, 2023 15:56
# Conflicts:
#	README.md
#	config/di.php
#	config/params.php
#	src/Middleware/FailureHandling/Implementation/ExponentialDelayMiddleware.php
#	src/Middleware/FailureHandling/Implementation/SendAgainMiddleware.php
#	src/Queue.php
#	src/Worker/Worker.php
#	tests/App/FakeHandler.php
#	tests/Integration/MessageConsumingTest.php
#	tests/Integration/MiddlewareTest.php
#	tests/TestCase.php
#	tests/Unit/QueueTest.php
#	tests/Unit/SynchronousAdapterTest.php
#	tests/Unit/WorkerTest.php
StyleCIBot and others added 9 commits February 2, 2024 07:41
# Conflicts:
#	config/di.php
#	config/params.php
#	src/Message/EnvelopeTrait.php
#	src/Message/JsonMessageSerializer.php
#	src/QueueInterface.php
#	src/Worker/Worker.php
#	tests/App/FakeHandler.php
#	tests/TestCase.php
#	tests/Unit/EnvelopeTest.php
#	tests/Unit/Message/JsonMessageSerializerTest.php
#	tests/Unit/Middleware/FailureHandling/MiddlewareFactoryTest.php
#	tests/Unit/WorkerTest.php
Copy link

codecov bot commented Feb 4, 2024

Codecov Report

Attention: Patch coverage is 61.11111% with 70 lines in your changes missing coverage. Please review.

Project coverage is 77.24%. Comparing base (b47a41f) to head (453c219).
Report is 20 commits behind head on master.

Files with missing lines Patch % Lines
config/di.php 0.00% 27 Missing ⚠️
src/Message/HandlerEnvelope.php 0.00% 10 Missing ⚠️
config/events-console.php 0.00% 8 Missing ⚠️
config/events-web.php 0.00% 8 Missing ⚠️
src/Message/EnvelopeTrait.php 38.46% 8 Missing ⚠️
src/Message/JsonMessageSerializer.php 64.28% 5 Missing ⚠️
src/Debug/QueueDecorator.php 0.00% 2 Missing ⚠️
config/queue.php 0.00% 1 Missing ⚠️
src/Worker/Worker.php 93.33% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master     #190      +/-   ##
============================================
- Coverage     84.65%   77.24%   -7.41%     
+ Complexity      372      284      -88     
============================================
  Files            47       45       -2     
  Lines          1088      914     -174     
============================================
- Hits            921      706     -215     
- Misses          167      208      +41     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

@viktorprogger
Copy link
Contributor

Some ideas were implemented in separate PRs, and some are not applicable. Closing this PR.

@samdark samdark deleted the new branch November 24, 2024 17:01
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.

3 participants