public function create($connection) { if (!array_key_exists('type', $connection)) { return $this->apiProblem(422, "No type given for the connection"); } if (!array_key_exists('message_handler', $connection)) { return $this->apiProblem(422, "No message_handler given for the connection"); } if (!array_key_exists('workflow_id', $connection)) { return $this->apiProblem(422, "No workflow_id given for the connection"); } if ($connection['type'] == "start_connection") { if (!array_key_exists('start_message', $connection)) { return $this->apiProblem(422, "No start_message given for the connection"); } $this->commandBus->dispatch(ScheduleFirstTasksForWorkflow::withData($connection['workflow_id'], $connection['start_message'], $connection['message_handler'])); return $this->accepted(); } elseif ($connection['type'] == "source_target_connection") { if (!array_key_exists('previous_task', $connection)) { return $this->apiProblem(422, "No previous_task given for the connection"); } $this->commandBus->dispatch(ScheduleNextTasksForWorkflow::withData($connection['workflow_id'], $connection['previous_task'], $connection['message_handler'])); return $this->accepted(); } else { return $this->apiProblem(422, "Unknown connection type"); } }
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { $path = $request->getUri()->getPath(); if (!isset($this->commands[$path])) { return $next($request, $response); } if ($request->getMethod() !== 'POST') { return $response->withStatus(405); } try { $payload = json_decode($request->getBody(), true); if ($payload === null) { $payload = []; } $command = $this->commands[$path]; if (!is_callable($command)) { throw new \RuntimeException("Command associated with the path {$path} is not callable"); } $command = call_user_func_array($command, [$payload]); $this->commandBus->dispatch($command); return $response->withStatus(202); } catch (CommandDispatchException $dispatchException) { $e = $dispatchException->getFailedCommandDispatch()->getException(); return $this->populateError($response, $e); } catch (\Exception $e) { return $this->populateError($response, $e); } }
/** * @param ActionEvent $event */ public function onEventStoreCommitPost(ActionEvent $event) { $commands = $this->commandQueue; $this->commandQueue = []; foreach ($commands as $command) { $this->innerCommandBus->dispatch($command); } }
public function update($id, $data) { if (!array_key_exists('metadata', $data)) { return $this->apiProblem(422, "No metadata given for the task"); } $this->commandBus->dispatch(UpdateTaskMetadata::to($data['metadata'], $id)); return $this->accepted(); }
/** * @param BernardMessage $message */ public function routeMessage(BernardMessage $message) { $proophMessage = $message->getProophMessage(); if ($proophMessage->messageType() === Message::TYPE_COMMAND) { $this->commandBus->dispatch($proophMessage); } else { $this->eventBus->dispatch($proophMessage); } }
public function create($data) { if (!array_key_exists('workflow_id', $data)) { return $this->apiProblem(422, "No workflow_id given for the release"); } $workflowData = $this->workflowFinder->find($data['workflow_id']); if (!$workflowData) { return $this->apiProblem(404, "Workflow can not be found"); } $newRelease = (int) $workflowData['current_release']; $newRelease++; $this->commandBus->dispatch(PublishWorkflow::withReleaseNumber($newRelease, $data['workflow_id'])); return $this->location($this->url()->fromRoute('prooph.link/process_config/api/workflow_release', ['id' => $newRelease])); }
/** * @interitdoc */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $commandName = $request->getAttribute(self::NAME_ATTRIBUTE); if (null === $commandName) { return $next($request, $response, new RuntimeException(sprintf('Command name attribute ("%s") was not found in request.', self::NAME_ATTRIBUTE), Middleware::STATUS_CODE_BAD_REQUEST)); } try { $command = $this->commandFactory->createMessageFromArray($commandName, ['payload' => $request->getParsedBody(), 'metadata' => $this->metadataGatherer->getFromRequest($request)]); $this->commandBus->dispatch($command); return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED); } catch (\Exception $e) { return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of command "%s"', $commandName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e)); } }
public function update($id, $data) { if (!array_key_exists('name', $data)) { return $this->apiProblem(422, "No name given for the workflow"); } try { $this->commandBus->dispatch(ChangeWorkflowName::to($data['name'], $id)); } catch (CommandDispatchException $ex) { if ($ex->getFailedCommandDispatch()->getException() instanceof WorkflowNotFound) { return $this->apiProblem(404, "Workflow not found"); } else { throw $ex->getFailedCommandDispatch()->getException(); } } return $this->accepted(); }
/** * @test */ public function it_sends_remove_file_command_to_file_remover_via_php_resque() { $this->assertTrue(file_exists($this->testFile)); $commandBus = new CommandBus(); $commandRouter = new CommandRouter(); $messageDispatcher = new MessageDispatcher(['track_job_status' => true, 'queue' => 'php-resque-test-queue']); $commandRouter->route('Prooph\\ServiceBusTest\\Mock\\RemoveFileCommand')->to($messageDispatcher); $commandBus->utilize($commandRouter); $commandBus->utilize(new ForwardToRemoteMessageDispatcherStrategy(new ProophDomainMessageToRemoteMessageTranslator())); $jobId = null; $messageDispatcher->events()->attach('dispatch.post', function (EventInterface $e) use(&$jobId) { $jobId = $e->getParam('jobId'); }); $removeFile = RemoveFileCommand::fromPayload($this->testFile); $commandBus->dispatch($removeFile); $this->assertNotNull($jobId); $status = new \Resque_Job_Status($jobId); $this->assertEquals(\Resque_Job_Status::STATUS_WAITING, $status->get()); $worker = new \Resque_Worker(array('php-resque-test-queue')); $worker->logLevel = 1; $worker->work(0); $worker->shutdown(); $this->assertEquals(\Resque_Job_Status::STATUS_COMPLETE, $status->get()); $this->assertFalse(file_exists($this->testFile)); }
/** * @test * @expectedException Prooph\ServiceBus\Exception\RuntimeException */ public function it_throws_exception_if_event_has_no_handler_after_it_has_been_set_and_event_was_triggered() { $this->commandBus->getActionEventEmitter()->attachListener(MessageBus::EVENT_INITIALIZE, function (ActionEvent $e) { $e->setParam(QueryBus::EVENT_PARAM_MESSAGE_HANDLER, null); }); $this->commandBus->dispatch("throw it"); }
/** * @interitdoc */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $payload = null; $messageName = 'UNKNOWN'; try { $payload = $request->getParsedBody(); if (is_array($payload) && isset($payload['message_name'])) { $messageName = $payload['message_name']; } MessageDataAssertion::assert($payload); $message = $this->messageFactory->createMessageFromArray($payload['message_name'], $payload); switch ($message->messageType()) { case Message::TYPE_COMMAND: $this->commandBus->dispatch($message); return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED); case Message::TYPE_EVENT: $this->eventBus->dispatch($message); return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED); case Message::TYPE_QUERY: return $this->responseStrategy->fromPromise($this->queryBus->dispatch($message)); default: return $next($request, $response, new RuntimeException(sprintf('Invalid message type "%s" for message "%s".', $message->messageType(), $messageName), Middleware::STATUS_CODE_BAD_REQUEST)); } } catch (\Assert\InvalidArgumentException $e) { return $next($request, $response, new RuntimeException($e->getMessage(), Middleware::STATUS_CODE_BAD_REQUEST, $e)); } catch (\Exception $e) { return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of message "%s"', $messageName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e)); } }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $commandName = $request->getAttribute('command'); if (!$commandName) { return $next($request, $response); } try { $payload = $this->getPayloadFromRequest($request); $command = $this->commandFactory->createMessageFromArray($commandName, ['payload' => $payload]); $this->commandBus->dispatch($command); return $response->withStatus(202); } catch (MessageDispatchException $dispatchException) { $e = $dispatchException->getFailedDispatchEvent()->getParam('exception'); return $this->populateError($response, $e); } catch (\Exception $e) { return $this->populateError($response, $e); } }
/** * Perform a message */ public function perform() { $messageClass = $this->args['message_class']; /* @var $message \Prooph\Common\Messaging\RemoteMessage*/ $message = $messageClass::fromArray($this->args['message_data']); if ($message->header()->type() === MessageHeader::TYPE_COMMAND) { try { $this->commandBus->dispatch($message); } catch (CommandDispatchException $ex) { throw $ex->getPrevious(); } } else { try { $this->eventBus->dispatch($message); } catch (EventDispatchException $ex) { throw $ex->getPrevious(); } } }
public function create($data) { if (!array_key_exists('name', $data)) { return $this->apiProblem(422, "No name given for the message handler"); } if (!array_key_exists('node_name', $data)) { return $this->apiProblem(422, "No node_name given for the message handler"); } if (!array_key_exists('type', $data)) { return $this->apiProblem(422, "No type given for the message handler"); } if (!array_key_exists('data_direction', $data)) { return $this->apiProblem(422, "No data_direction given for the message handler"); } if (!array_key_exists('metadata_riot_tag', $data)) { return $this->apiProblem(422, "No metadata_riot_tag given for the message handler"); } if (!array_key_exists('icon', $data)) { return $this->apiProblem(422, "No icon given for the message handler"); } if (!array_key_exists('icon_type', $data)) { return $this->apiProblem(422, "No icon_type given for the message handler"); } if (!isset($data['processing_types'])) { $data['processing_types'] = ProcessingTypes::SUPPORT_ALL; } if (!isset($data['processing_metadata'])) { $data['processing_metadata'] = ProcessingMetadata::noData()->toArray(); } if (!isset($data['preferred_type'])) { $data['preferred_type'] = null; } if (!isset($data['processing_id'])) { $data['processing_id'] = null; } if (!isset($data['additional_data'])) { $data['additional_data'] = []; } $messageHandlerId = MessageHandlerId::generate(); $this->commandBus->dispatch(InstallMessageHandler::withData($messageHandlerId, $data['name'], $data['node_name'], $data['type'], $data['data_direction'], $data['processing_types'], $data['processing_metadata'], $data['metadata_riot_tag'], $data['icon'], $data['icon_type'], $data['preferred_type'], $data['processing_id'], $data['additional_data'])); return $this->location($this->url()->fromRoute('prooph.link/process_config/api/message_handler', ['id' => $messageHandlerId->toString()])); }
/** * @test */ public function it_invokes_processing_command_on_workflow_message_handler() { $wfCommand = WorkflowMessage::collectDataOf(UserDictionary::prototype(), 'test-case', NodeName::defaultName()); $commandBus = new CommandBus(); $commandRouter = new CommandRouter(); $commandRouter->route($wfCommand->messageName())->to($this->workflowMessageHandler); $commandBus->utilize($commandRouter); $commandBus->utilize(new HandleWorkflowMessageInvokeStrategy()); $commandBus->dispatch($wfCommand); $this->assertSame($wfCommand, $this->workflowMessageHandler->lastWorkflowMessage()); }
/** * Take snapshots on event-store::commit.post * * @param ActionEvent $actionEvent */ public function onEventStoreCommitPost(ActionEvent $actionEvent) { $recordedEvents = $actionEvent->getParam('recordedEvents', []); $snapshots = []; foreach ($recordedEvents as $recordedEvent) { if ($recordedEvent->version() % $this->versionStep !== 0) { continue; } $metadata = $recordedEvent->metadata(); if (!isset($metadata['aggregate_type']) || !isset($metadata['aggregate_id'])) { continue; } $snapshots[$metadata['aggregate_type']][] = $metadata['aggregate_id']; } foreach ($snapshots as $aggregateType => $aggregateIds) { foreach ($aggregateIds as $aggregateId) { $command = TakeSnapshot::withData($aggregateType, $aggregateId); $this->commandBus->dispatch($command); } } }
/** * @param Envelope $envelope * @param Queue $queue * @return DeliveryResult */ public function __invoke(Envelope $envelope, Queue $queue) : DeliveryResult { $data = json_decode($envelope->getBody(), true); if (!isset($data['created_at'])) { return DeliveryResult::MSG_REJECT(); } $data['created_at'] = DateTimeImmutable::createFromFormat('Y-m-d\\TH:i:s.u', $data['created_at'], new DateTimeZone('UTC')); if (false === $data['created_at']) { return DeliveryResult::MSG_REJECT(); } try { $command = $this->messageFactory->createMessageFromArray($envelope->getType(), $data); $this->commandBus->dispatch($command); } catch (\Throwable $e) { while ($e = $e->getPrevious()) { if ($e instanceof ConcurrencyException) { return DeliveryResult::MSG_REJECT_REQUEUE(); } } return DeliveryResult::MSG_REJECT(); } return DeliveryResult::MSG_ACK(); }
/** * @param mixed $id * @param array $data * @return array|mixed|null|ApiProblemResponse */ public function update($id, array $data) { if (!$this->existsConnector($id)) { return new ApiProblemResponse(new ApiProblem(404, 'Connector can not be found')); } $data['ui_metadata_riot_tag'] = self::UI_METADATA_RIOT_TAG; $data['icon'] = self::ICON; $result = $this->validateConnectorData($data); if ($result instanceof ApiProblemResponse) { return $result; } $data = FileGatewayTranslator::translateFromClient($data); $this->commandBus->dispatch(ChangeConnectorConfig::ofConnector($id, $data, $this->systemConfig->getConfigLocation())); $data = FileGatewayTranslator::translateToClient($data); $data['id'] = $id; return $data; }
/** * @param MessageHandler $messageHandler */ private function syncMessageHandler(MessageHandler $messageHandler) { $additionalData = $messageHandler->additionalData(); if ($messageHandler->preferredProcessingType()) { $additionalData['preferred_type'] = $messageHandler->preferredProcessingType()->of(); } $additionalData['node_name'] = $messageHandler->processingNodeName()->toString(); $additionalData['icon'] = $messageHandler->icon(); $additionalData['icon_type'] = $messageHandler->iconType(); $additionalData['metadata'] = $messageHandler->processingMetadata()->toArray(); $additionalData['ui_metadata_riot_tag'] = $messageHandler->metadataRiotTag(); $allowedTypes = $messageHandler->supportedProcessingTypes()->areAllTypesSupported() ? MessageHandler\ProcessingTypes::SUPPORT_ALL : $messageHandler->supportedProcessingTypes()->typeList(); if ($messageHandler->isKnownInProcessingSystem()) { $this->commandBus->dispatch(ChangeConnectorConfig::ofConnector($messageHandler->processingId()->toString(), array_merge(['name' => $messageHandler->name(), 'allowed_messages' => $this->determineAllowedMessages($messageHandler), 'allowed_types' => $allowedTypes], $additionalData), $this->processingConfigLocation)); } else { $this->commandBus->dispatch(AddConnectorToConfig::fromDefinition($messageHandler->processingId()->toString(), $messageHandler->name(), $this->determineAllowedMessages($messageHandler), $allowedTypes, $this->processingConfigLocation, $additionalData)); } }
/** * @test */ public function it_passes_queued_commands_to_command_dispatch_exception_in_case_of_an_error() { $messageHandler = new MessageHandler(); $this->commandBus->utilize((new CommandRouter())->route(CustomMessage::class)->to($messageHandler)->route('initial message')->to(function () use($messageHandler) { $delayedMessage = new CustomMessage("delayed message"); $this->commandBus->dispatch($delayedMessage); throw new \Exception("Ka Boom"); })); $commandDispatchException = null; try { $this->commandBus->dispatch('initial message'); } catch (CommandDispatchException $ex) { $commandDispatchException = $ex; } $this->assertInstanceOf(CommandDispatchException::class, $commandDispatchException); $this->assertSame(1, count($commandDispatchException->getPendingCommands())); $this->assertSame(CustomMessage::class, get_class($commandDispatchException->getPendingCommands()[0])); }
public function updateConnector($id, array $connector, $regenerateType = false) { $this->assertConnector($connector); if (!$this->dbalConnections->containsKey($connector['dbal_connection'])) { throw new \InvalidArgumentException(sprintf("Dbal connection %s for connector %s does not exists", $connector['dbal_connection'], $connector['name'])); } $connection = $this->dbalConnections->get($connector['dbal_connection']); if ($regenerateType) { $generatedTypes = $this->replaceProcessingTypes($connection->config()['dbname'], $connector['table'], $connection->connection()); } else { $generatedTypes = $this->generateTypeClassFQCNs($connection->config()['dbname'], $connector['table']); } $connector['icon'] = self::ICON; $connector['ui_metadata_riot_tag'] = self::METADATA_UI_KEY; $connector['allowed_types'] = $generatedTypes; $connector['allowed_messages'] = [MessageNameUtils::COLLECT_DATA, MessageNameUtils::PROCESS_DATA]; $command = ChangeConnectorConfig::ofConnector($id, $connector, $this->configLocation); $this->commandBus->dispatch($command); }
/** * Take snapshots on event-store::commit.post * * @param ActionEvent $actionEvent */ public function onEventStoreCommitPost(ActionEvent $actionEvent) { $recordedEvents = $actionEvent->getParam('recordedEvents', new \ArrayIterator()); $snapshots = []; /* @var $recordedEvent \Prooph\Common\Messaging\Message */ foreach ($recordedEvents as $recordedEvent) { $doSnapshot = $recordedEvent->version() % $this->versionStep === 0; if (false === $doSnapshot && false === $this->hasEventNames) { continue; } $metadata = $recordedEvent->metadata(); if (!isset($metadata['aggregate_type'], $metadata['aggregate_id']) || false === $doSnapshot && !in_array($recordedEvent->messageName(), $this->eventNames, true)) { continue; } $snapshots[$metadata['aggregate_type']][] = $metadata['aggregate_id']; } foreach ($snapshots as $aggregateType => $aggregateIds) { foreach ($aggregateIds as $aggregateId) { $command = TakeSnapshot::withData($aggregateType, $aggregateId); $this->commandBus->dispatch($command); } } }
} /** * This method is called when message is instantiated named constructor fromArray * * @param array $payload * @return void */ protected function setPayload(array $payload) { $this->text = $payload['text']; } } } namespace { use Prooph\ServiceBus\CommandBus; use Prooph\ServiceBus\Example\Command\EchoText; use Prooph\ServiceBus\Plugin\Router\CommandRouter; $commandBus = new CommandBus(); $router = new CommandRouter(); //Register a callback as CommandHandler for the EchoText command $router->route('Prooph\\ServiceBus\\Example\\Command\\EchoText')->to(function (EchoText $aCommand) { echo $aCommand->getText(); }); //Expand command bus with the router plugin $commandBus->utilize($router); //We create a new Command $echoText = new EchoText('It works'); //... and dispatch it $commandBus->dispatch($echoText); //Output should be: It works }
/** * @test */ public function it_sends_a_start_sub_process_command_via_message_dispatcher_to_a_handler() { $taskListPosition = TaskListPosition::at(TaskListId::linkWith(NodeName::defaultName(), ProcessId::generate()), 1); $startSupProcess = StartSubProcess::at($taskListPosition, ['process_type' => 'faked'], true, 'sub-processor'); $commandBus = new CommandBus(); $commandRouter = new CommandRouter(); $commandRouter->route(StartSubProcess::MSG_NAME)->to($this->messageDispatcher); $commandBus->utilize($commandRouter); $commandBus->utilize(new ForwardToRemoteMessageDispatcherStrategy(new FromProcessingMessageTranslator())); $commandBus->dispatch($startSupProcess); /** @var $receivedMessage StartSubProcess */ $receivedMessage = $this->receivedMessage; $this->assertInstanceOf(get_class($startSupProcess), $receivedMessage); $this->assertTrue($taskListPosition->equals($receivedMessage->parentTaskListPosition())); $this->assertTrue($startSupProcess->uuid()->equals($receivedMessage->uuid())); $this->assertEquals($startSupProcess->payload(), $receivedMessage->payload()); $this->assertEquals($startSupProcess->createdAt()->format('Y-m-d H:i:s'), $receivedMessage->createdAt()->format('Y-m-d H:i:s')); $this->assertEquals($startSupProcess->target(), $receivedMessage->target()); }
$commandBus = new CommandBus(); $messageDispatcher = new MessageDispatcher(['track_job_status' => true, 'queue' => 'resque-sample']); $commandBus->utilize(new RegexRouter([RegexRouter::ALL => $messageDispatcher])); $commandBus->utilize(new ForwardToRemoteMessageDispatcherStrategy(new ProophDomainMessageToRemoteMessageTranslator())); //The PhpResqueMessageDispatcher uses a Redis-Server to manage background jobs //We want to track the status of the job and therefor we use the event system of MessageDispatcher to capture the JobId //of a new created Job $jobId = null; //After the MessageDispatcher has done it's work, we capture the JobId with an EventListener $messageDispatcher->events()->attach('dispatch.post', function (EventInterface $e) use(&$jobId) { $jobId = $e->getParam('jobId'); }); //Prepare the Command $writeLine = WriteLine::fromPayload($_GET['write']); //...and send it to the message dispatcher via CommandBus $commandBus->dispatch($writeLine); echo 'Message is sent with JobId: ' . $jobId . '. You can check the status with ' . strtok($_SERVER["REQUEST_URI"], '?') . '<b>?status=' . $jobId . '</b>'; } elseif (isset($_GET['status'])) { $status = new \Resque_Job_Status($_GET['status']); switch ($status->get()) { case \Resque_Job_Status::STATUS_WAITING: echo 'Status: waiting. If you did not start a worker yet, than open a console, and run: <b>php ' . __DIR__ . '/start-worker.php</b>'; break; case \Resque_Job_Status::STATUS_RUNNING: echo 'Status: running. Wait a moment, the job should finish soon.'; break; case \Resque_Job_Status::STATUS_COMPLETE: echo 'Status: complete. You should see a new line with your text, when you open: <b>' . strtok($_SERVER["REQUEST_URI"], '?') . '</b>'; break; case \Resque_Job_Status::STATUS_FAILED: echo "Status failed: Something went wrong. Stop current worker. Try again writing some text with: " . strtok($_SERVER["REQUEST_URI"], '?') . "<b>?write=some text</b>' " . "and start a new worker with this command: <b>VVERBOSE=1 php " . __DIR__ . "/start-worker.php</b>. " . "You should be able to see the error which causes the job to fail.";