From 689ca9cbadd0df0205054c600048e2642a24d3d8 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 31 Mar 2021 17:25:24 +0300 Subject: [PATCH] lockable middleware --- Messenger/CommandMessage.php | 14 +++++ Messenger/Middleware/LockableMessage.php | 13 +++++ .../Middleware/LockableMessageMiddleware.php | 58 +++++++++++++++++++ composer.json | 3 +- 4 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 Messenger/Middleware/LockableMessage.php create mode 100644 Messenger/Middleware/LockableMessageMiddleware.php diff --git a/Messenger/CommandMessage.php b/Messenger/CommandMessage.php index 9ea7cde..06b6efb 100644 --- a/Messenger/CommandMessage.php +++ b/Messenger/CommandMessage.php @@ -96,4 +96,18 @@ abstract class CommandMessage return $options; } + + /** + * For lockable message + * + * @return array + */ + public function __serialize(): array + { + return [ + 'command' => $this->getCommandName(), + 'arguments' => $this->getArguments(), + 'options' => $this->getOptions() + ]; + } } diff --git a/Messenger/Middleware/LockableMessage.php b/Messenger/Middleware/LockableMessage.php new file mode 100644 index 0000000..9550df3 --- /dev/null +++ b/Messenger/Middleware/LockableMessage.php @@ -0,0 +1,13 @@ +lockFactory = $lockFactory; + } + + /** + * @param Envelope $envelope + * @param StackInterface $stack + * + * @return Envelope + * + * @throws Throwable + */ + public function handle(Envelope $envelope, StackInterface $stack): Envelope + { + $message = $envelope->getMessage(); + + if ($envelope->all(ReceivedStamp::class) && $message instanceof LockableMessage) { + $lock = $this->lockFactory->createLock(md5(serialize($message))); + if (!$lock->acquire()) { + return $envelope; + } + + try { + return $stack->next()->handle($envelope, $stack); + } catch (Throwable $exception) { + throw $exception; + } finally { + $lock->release(); + } + } + + return $stack->next()->handle($envelope, $stack); + } +} diff --git a/composer.json b/composer.json index c90c1ab..9fbbf2e 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,8 @@ "symfony/console": "^5.2", "symfony/messenger": "^5.2", "symfony/process": "^5.2", - "symfony/event-dispatcher": "^5.2" + "symfony/event-dispatcher": "^5.2", + "symfony/lock": "^5.2" }, "autoload": { "psr-4": {