QueueManagement.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\MysqlMq\Model;
  7. /**
  8. * Main class for managing MySQL implementation of message queue.
  9. *
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class QueueManagement
  14. {
  15. const MESSAGE_TOPIC = 'topic_name';
  16. const MESSAGE_BODY = 'body';
  17. const MESSAGE_ID = 'message_id';
  18. const MESSAGE_STATUS = 'status';
  19. const MESSAGE_UPDATED_AT = 'updated_at';
  20. const MESSAGE_QUEUE_ID = 'queue_id';
  21. const MESSAGE_QUEUE_NAME = 'queue_name';
  22. const MESSAGE_QUEUE_RELATION_ID = 'relation_id';
  23. const MESSAGE_NUMBER_OF_TRIALS = 'retries';
  24. const MESSAGE_STATUS_NEW = 2;
  25. const MESSAGE_STATUS_IN_PROGRESS = 3;
  26. const MESSAGE_STATUS_COMPLETE= 4;
  27. const MESSAGE_STATUS_RETRY_REQUIRED = 5;
  28. const MESSAGE_STATUS_ERROR = 6;
  29. const MESSAGE_STATUS_TO_BE_DELETED = 7;
  30. /**#@+
  31. * Cleanup configuration XML nodes
  32. */
  33. const XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME = 'system/mysqlmq/successful_messages_lifetime';
  34. const XML_PATH_FAILED_MESSAGES_LIFETIME = 'system/mysqlmq/failed_messages_lifetime';
  35. const XML_PATH_RETRY_IN_PROGRESS_AFTER = 'system/mysqlmq/retry_inprogress_after';
  36. const XML_PATH_NEW_MESSAGES_LIFETIME = 'system/mysqlmq/new_messages_lifetime';
  37. /**#@-*/
  38. /**#@-*/
  39. private $messageResource;
  40. /**
  41. * @var \Magento\Framework\App\Config\ScopeConfigInterface
  42. */
  43. private $scopeConfig;
  44. /**
  45. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  46. */
  47. private $dateTime;
  48. /**
  49. * @var \Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory
  50. */
  51. private $messageStatusCollectionFactory;
  52. /**
  53. * @param \Magento\MysqlMq\Model\ResourceModel\Queue $messageResource
  54. * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  55. * @param \Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory $messageStatusCollectionFactory
  56. * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
  57. */
  58. public function __construct(
  59. \Magento\MysqlMq\Model\ResourceModel\Queue $messageResource,
  60. \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  61. \Magento\MysqlMq\Model\ResourceModel\MessageStatusCollectionFactory $messageStatusCollectionFactory,
  62. \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
  63. ) {
  64. $this->messageResource = $messageResource;
  65. $this->scopeConfig = $scopeConfig;
  66. $this->dateTime = $dateTime;
  67. $this->messageStatusCollectionFactory = $messageStatusCollectionFactory;
  68. }
  69. /**
  70. * Add message to all specified queues.
  71. *
  72. * @param string $topic
  73. * @param string $message
  74. * @param string[] $queueNames
  75. * @return $this
  76. */
  77. public function addMessageToQueues($topic, $message, $queueNames)
  78. {
  79. $messageId = $this->messageResource->saveMessage($topic, $message);
  80. $this->messageResource->linkQueues($messageId, $queueNames);
  81. return $this;
  82. }
  83. /**
  84. * Add messages to all specified queues.
  85. *
  86. * @param string $topic
  87. * @param array $messages
  88. * @param string[] $queueNames
  89. * @return $this
  90. * @since 100.2.0
  91. */
  92. public function addMessagesToQueues($topic, $messages, $queueNames)
  93. {
  94. $messageIds = $this->messageResource->saveMessages($topic, $messages);
  95. $this->messageResource->linkMessagesWithQueues($messageIds, $queueNames);
  96. return $this;
  97. }
  98. /**
  99. * Delete marked messages
  100. *
  101. * Mark messages to be deleted if sufficient amount of time passed since last update
  102. *
  103. * @return void
  104. */
  105. public function markMessagesForDelete()
  106. {
  107. $collection = $this->messageStatusCollectionFactory->create()
  108. ->addFieldToFilter(
  109. 'status',
  110. ['in' => $this->getStatusesToClear()]
  111. );
  112. /**
  113. * Update messages if lifetime is expired
  114. */
  115. foreach ($collection as $messageStatus) {
  116. $this->processMessagePerStatus($messageStatus);
  117. }
  118. /**
  119. * Delete all messages which has To BE DELETED status in all the queues
  120. */
  121. $this->messageResource->deleteMarkedMessages();
  122. }
  123. /**
  124. * Based on message status, updated date and timeout for the status, move it to next state
  125. *
  126. * @param MessageStatus $messageStatus
  127. * @return void
  128. */
  129. private function processMessagePerStatus($messageStatus)
  130. {
  131. $now = $this->dateTime->gmtTimestamp();
  132. if ($messageStatus->getStatus() == self::MESSAGE_STATUS_COMPLETE
  133. && strtotime($messageStatus->getUpdatedAt()) < ($now - $this->getCompletedMessageLifetime())) {
  134. $messageStatus->setStatus(self::MESSAGE_STATUS_TO_BE_DELETED)
  135. ->save();
  136. } elseif ($messageStatus->getStatus() == self::MESSAGE_STATUS_ERROR
  137. && strtotime($messageStatus->getUpdatedAt()) < ($now - $this->getErrorMessageLifetime())) {
  138. $messageStatus->setStatus(self::MESSAGE_STATUS_TO_BE_DELETED)
  139. ->save();
  140. } elseif ($messageStatus->getStatus() == self::MESSAGE_STATUS_IN_PROGRESS
  141. && strtotime($messageStatus->getUpdatedAt()) < ($now - $this->getInProgressRetryAfter())
  142. ) {
  143. $this->pushToQueueForRetry($messageStatus->getId());
  144. } elseif ($messageStatus->getStatus() == self::MESSAGE_STATUS_NEW
  145. && strtotime($messageStatus->getUpdatedAt()) < ($now - $this->getNewMessageLifetime())
  146. ) {
  147. $messageStatus->setStatus(self::MESSAGE_STATUS_TO_BE_DELETED)
  148. ->save();
  149. }
  150. }
  151. /**
  152. * Compose a set of statuses to track for deletion based on configuration.
  153. *
  154. * @return array
  155. */
  156. private function getStatusesToClear()
  157. {
  158. /**
  159. * Do not mark messages for deletion if configuration has 0 lifetime configured.
  160. */
  161. $statusesToDelete = [];
  162. if ($this->getCompletedMessageLifetime() > 0) {
  163. $statusesToDelete[] = self::MESSAGE_STATUS_COMPLETE;
  164. }
  165. if ($this->getErrorMessageLifetime() > 0) {
  166. $statusesToDelete[] = self::MESSAGE_STATUS_ERROR;
  167. }
  168. if ($this->getNewMessageLifetime() > 0) {
  169. $statusesToDelete[] = self::MESSAGE_STATUS_NEW;
  170. }
  171. if ($this->getInProgressRetryAfter() > 0) {
  172. $statusesToDelete[] = self::MESSAGE_STATUS_IN_PROGRESS;
  173. }
  174. return $statusesToDelete;
  175. }
  176. /**
  177. * Completed message lifetime
  178. *
  179. * Indicates how long message in COMPLETE state will stay in table with statuses
  180. *
  181. * @return int
  182. */
  183. private function getCompletedMessageLifetime()
  184. {
  185. return 60 * (int)$this->scopeConfig->getValue(
  186. self::XML_PATH_SUCCESSFUL_MESSAGES_LIFETIME,
  187. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  188. );
  189. }
  190. /**
  191. * Failure message life time
  192. *
  193. * Indicates how long message in ERROR state will stay in table with statuses
  194. *
  195. * @return int
  196. */
  197. private function getErrorMessageLifetime()
  198. {
  199. return 60 * (int)$this->scopeConfig->getValue(
  200. self::XML_PATH_FAILED_MESSAGES_LIFETIME,
  201. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  202. );
  203. }
  204. /**
  205. * In progress message delay before retry
  206. *
  207. * Indicates how long message will stay in IN PROGRESS status before attempted to retry
  208. *
  209. * @return int
  210. */
  211. private function getInProgressRetryAfter()
  212. {
  213. return 60 * (int)$this->scopeConfig->getValue(
  214. self::XML_PATH_RETRY_IN_PROGRESS_AFTER,
  215. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  216. );
  217. }
  218. /**
  219. * New message life time
  220. *
  221. * Indicates how long message in NEW state will stay in table with statuses
  222. *
  223. * @return int
  224. */
  225. private function getNewMessageLifetime()
  226. {
  227. return 60 * (int)$this->scopeConfig->getValue(
  228. self::XML_PATH_NEW_MESSAGES_LIFETIME,
  229. \Magento\Store\Model\ScopeInterface::SCOPE_STORE
  230. );
  231. }
  232. /**
  233. * Read the specified number of messages from the specified queue.
  234. *
  235. * If queue does not contain enough messages, method is not waiting for more messages.
  236. *
  237. * @param string $queue
  238. * @param int|null $maxMessagesNumber
  239. * @return array <pre>
  240. * [
  241. * [
  242. * self::MESSAGE_ID => $messageId,
  243. * self::MESSAGE_QUEUE_ID => $queuId,
  244. * self::MESSAGE_TOPIC => $topic,
  245. * self::MESSAGE_BODY => $body,
  246. * self::MESSAGE_STATUS => $status,
  247. * self::MESSAGE_UPDATED_AT => $updatedAt,
  248. * self::MESSAGE_QUEUE_NAME => $queueName
  249. * self::MESSAGE_QUEUE_RELATION_ID => $relationId
  250. * ],
  251. * ...
  252. * ]</pre>
  253. */
  254. public function readMessages($queue, $maxMessagesNumber = null)
  255. {
  256. $selectedMessages = $this->messageResource->getMessages($queue, $maxMessagesNumber);
  257. /* The logic below allows to prevent the same message being processed by several consumers in parallel */
  258. $selectedMessagesRelatedIds = [];
  259. foreach ($selectedMessages as &$message) {
  260. /* Set message status here to avoid extra reading from DB after it is updated */
  261. $message[self::MESSAGE_STATUS] = self::MESSAGE_STATUS_IN_PROGRESS;
  262. $selectedMessagesRelatedIds[] = $message[self::MESSAGE_QUEUE_RELATION_ID];
  263. }
  264. $takenMessagesRelationIds = $this->messageResource->takeMessagesInProgress($selectedMessagesRelatedIds);
  265. if (count($selectedMessages) == count($takenMessagesRelationIds)) {
  266. return $selectedMessages;
  267. } else {
  268. $selectedMessages = array_combine($selectedMessagesRelatedIds, array_values($selectedMessages));
  269. return array_intersect_key($selectedMessages, array_flip($takenMessagesRelationIds));
  270. }
  271. }
  272. /**
  273. * Push message back to queue for one more processing trial. Affects message in particular queue only.
  274. *
  275. * @param int $messageRelationId
  276. * @return void
  277. */
  278. public function pushToQueueForRetry($messageRelationId)
  279. {
  280. $this->messageResource->pushBackForRetry($messageRelationId);
  281. }
  282. /**
  283. * Change status of messages.
  284. *
  285. * @param int[] $messageRelationIds
  286. * @param int $status
  287. * @return void
  288. */
  289. public function changeStatus($messageRelationIds, $status)
  290. {
  291. $this->messageResource->changeStatus($messageRelationIds, $status);
  292. }
  293. }