protected function setUp() { parent::setUp(); $eventBus = new EventBus(); $commandBus = new CommandBus(); $commandRouter = new CommandRouter(); $commandRouter->route(StartSubProcess::MSG_NAME)->to(function (StartSubProcess $command) { $this->receivedMessage = $command; }); $commandRouter->route('processing-message-proophprocessingtestmockuserdictionary-collect-data')->to(function (WorkflowMessage $message) { $this->receivedMessage = $message; }); $commandBus->utilize($commandRouter); $commandBus->utilize(new ToProcessingMessageTranslator()); $commandBus->utilize(new CallbackStrategy()); $eventRouter = new EventRouter(); $eventRouter->route('processing-message-proophprocessingtestmockuserdictionary-data-collected')->to(function (WorkflowMessage $workflowMessage) { $this->receivedMessage = $workflowMessage; }); $eventRouter->route('processing-log-message')->to(function (LogMessage $logMessage) { $this->receivedMessage = $logMessage; }); $eventRouter->route(SubProcessFinished::MSG_NAME)->to(function (SubProcessFinished $event) { $this->receivedMessage = $event; }); $eventBus->utilize($eventRouter); $eventBus->utilize(new ToProcessingMessageTranslator()); $eventBus->utilize(new CallbackStrategy()); $this->workflowEngine = new RegistryWorkflowEngine(); $this->workflowEngine->registerCommandBus($commandBus, [NodeName::defaultName()->toString(), 'test-target', 'sub-processor']); $this->workflowEngine->registerEventBus($eventBus, [NodeName::defaultName()->toString()]); }
/** * @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)); }
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); } }
/** * @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()); }
protected function setUp() { $commandBus = new CommandBus(); $commandRouter = new CommandRouter(); $commandRouter->route(StartSubProcess::MSG_NAME)->to(function ($command) { $this->startSubProcessCommands[] = $command; }); $commandBus->utilize($commandRouter); $commandBus->utilize(new CallbackStrategy()); $this->workflowEngine = new RegistryWorkflowEngine(); $this->workflowEngine->registerCommandBus($commandBus, [NodeName::defaultName()->toString()]); }
/** * @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 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) { $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)); } }
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(); }
protected function setUp() { UsersFixture::createTableAndInsertUsers($this->getDbalConnection()); $this->messageReceiver = new StupidWorkflowProcessorMock(); $this->commandBus = new CommandBus(); $this->commandBus->utilize(new SingleTargetMessageRouter($this->messageReceiver)); $this->commandBus->utilize(new WorkflowProcessorInvokeStrategy()); $this->eventBus = new EventBus(); $this->eventBus->utilize(new SingleTargetMessageRouter($this->messageReceiver)); $this->eventBus->utilize(new WorkflowProcessorInvokeStrategy()); $this->tableGateway = new DoctrineTableGateway($this->getDbalConnection(), self::TEST_TABLE); $this->workflowEngine = new RegistryWorkflowEngine(); $this->workflowEngine->registerCommandBus($this->commandBus, [NodeName::defaultName()->toString(), 'test-case']); $this->workflowEngine->registerEventBus($this->eventBus, [NodeName::defaultName()->toString(), 'test-case']); $this->tableGateway->useWorkflowEngine($this->workflowEngine); }
/** * @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"); }
protected function setUp() { $this->messageReceiver = new StupidWorkflowProcessorMock(); $this->commandBus = new CommandBus(); $this->commandBus->utilize(new SingleTargetMessageRouter($this->messageReceiver)); $this->commandBus->utilize(new WorkflowProcessorInvokeStrategy()); $this->eventBus = new EventBus(); $this->eventBus->utilize(new SingleTargetMessageRouter($this->messageReceiver)); $this->eventBus->utilize(new WorkflowProcessorInvokeStrategy()); $locationTranslator = new LocationTranslator(['temp' => sys_get_temp_dir(), 'testdata' => $this->getTestDataPath()]); $this->fileGateway = new FileGateway(Bootstrap::getServiceManager()->get('prooph.link.fileconnector.file_type_adapter_manager'), Bootstrap::getServiceManager()->get('prooph.link.fileconnector.filename_renderer'), $locationTranslator); $workflowEngine = new RegistryWorkflowEngine(); $workflowEngine->registerCommandBus($this->commandBus, [NodeName::defaultName()->toString(), 'file-connector']); $workflowEngine->registerEventBus($this->eventBus, [NodeName::defaultName()->toString(), 'file-connector']); $this->fileGateway->useWorkflowEngine($workflowEngine); $this->tempPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR; }
/** * @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()])); }
public function setUp() { $inMemoryAdapter = new InMemoryAdapter(); $eventEmitter = new ProophActionEventEmitter(); $this->eventStore = new EventStore($inMemoryAdapter, $eventEmitter); $this->repository = new AggregateRepository($this->eventStore, AggregateType::fromAggregateRootClass('ProophTest\\EventStore\\Mock\\User'), new ConfigurableAggregateTranslator()); $this->result = []; $self = $this; $router = new CommandRouter(); $router->route(TakeSnapshot::class)->to(function (TakeSnapshot $command) use($self) { $self->result[] = ['aggregate_type' => $command->aggregateType(), 'aggregate_id' => $command->aggregateId()]; }); $commandBus = new CommandBus(); $commandBus->utilize($router); $plugin = new SnapshotPlugin($commandBus, 2); $plugin->setUp($this->eventStore); $this->eventStore->beginTransaction(); $this->eventStore->create(new Stream(new StreamName('event_stream'), new \ArrayIterator())); $this->eventStore->commit(); }
/** * @test */ public function it_publishes_take_snapshot_commands_for_all_known_aggregates() { $inMemoryAdapter = new InMemoryAdapter(); $eventEmitter = new ProophActionEventEmitter(); $eventStore = new EventStore($inMemoryAdapter, $eventEmitter); $repository = new AggregateRepository($eventStore, AggregateType::fromAggregateRootClass('ProophTest\\EventStore\\Mock\\User'), new ConfigurableAggregateTranslator()); $result = []; $router = new CommandRouter(); $router->route(TakeSnapshot::class)->to(function (TakeSnapshot $command) use(&$result) { $result[] = ['aggregate_type' => $command->aggregateType(), 'aggregate_id' => $command->aggregateId()]; }); $commandBus = new CommandBus(); $commandBus->utilize($router); $plugin = new SnapshotPlugin($commandBus, 2); $plugin->setUp($eventStore); $eventStore->beginTransaction(); $eventStore->create(new Stream(new StreamName('event_stream'), new \ArrayIterator())); $eventStore->commit(); $eventStore->beginTransaction(); $user = User::create('Alex', '*****@*****.**'); $repository->addAggregateRoot($user); $eventStore->commit(); $eventStore->beginTransaction(); $user = $repository->getAggregateRoot($user->getId()->toString()); $user->changeName('John'); $user->changeName('Jane'); $user->changeName('Jim'); $eventStore->commit(); $eventStore->beginTransaction(); $eventWithoutMetadata1 = UsernameChanged::with(['new_name' => 'John Doe'], 5); $eventWithoutMetadata2 = UsernameChanged::with(['new_name' => 'Jane Doe'], 6); $eventStore->appendTo(new StreamName('event_stream'), new \ArrayIterator([$eventWithoutMetadata1, $eventWithoutMetadata2])); $eventStore->commit(); $this->assertCount(2, $result); $this->assertArrayHasKey('aggregate_type', $result[0]); $this->assertArrayHasKey('aggregate_id', $result[0]); $this->assertArrayHasKey('aggregate_type', $result[1]); $this->assertArrayHasKey('aggregate_id', $result[1]); $this->assertEquals(User::class, $result[0]['aggregate_type']); $this->assertEquals(User::class, $result[1]['aggregate_type']); }
/** * 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); } } }
/** * @test */ public function it_sends_a_command_to_queue_pulls_it_with_consumer_and_forwards_it_to_command_bus() { $command = new DoSomething(['data' => 'test command']); //The message dispatcher works with a ready-to-use bernard producer and one queue $messageProducer = new BernardMessageProducer($this->bernardProducer, 'test-queue'); //Normally you would send the command on a command bus. We skip this step here cause we are only //interested in the function of the message dispatcher $messageProducer($command); //Set up command bus which will receive the command message from the bernard consumer $consumerCommandBus = new CommandBus(); $doSomethingHandler = new MessageHandler(); $consumerCommandBus->utilize(new CommandRouter([$command->messageName() => $doSomethingHandler])); //We use a special bernard router which forwards all messages to a command bus or event bus depending on the //Prooph\ServiceBus\Message\MessageHeader::TYPE $bernardRouter = new BernardRouter($consumerCommandBus, new EventBus()); $bernardConsumer = new Consumer($bernardRouter, new EventDispatcher()); //We use the same queue name here as we've defined for the message dispatcher above $bernardConsumer->tick($this->persistentFactory->create('test-queue')); $this->assertNotNull($doSomethingHandler->getLastMessage()); $this->assertEquals($command->payload(), $doSomethingHandler->getLastMessage()->payload()); }
protected function setUpOtherMachine() { $this->otherMachineWorkflowMessageHandler = new TestWorkflowMessageHandler(); $commandBus = new CommandBus(); $this->otherMachineCommandRouter = new CommandRouter(); $this->otherMachineCommandRouter->route(MessageNameUtils::getCollectDataCommandName('Prooph\\ProcessingTest\\Mock\\UserDictionaryS2'))->to($this->otherMachineWorkflowMessageHandler); $this->otherMachineCommandRouter->route(MessageNameUtils::getProcessDataCommandName('Prooph\\ProcessingTest\\Mock\\TargetUserDictionary'))->to($this->otherMachineWorkflowMessageHandler); $commandBus->utilize($this->otherMachineCommandRouter); $commandBus->utilize(new HandleWorkflowMessageInvokeStrategy()); $commandBus->utilize(new WorkflowProcessorInvokeStrategy()); $commandBus->utilize(new ToProcessingMessageTranslator()); $this->otherMachineWorkflowEngine = new RegistryWorkflowEngine(); $this->otherMachineWorkflowEngine->registerCommandBus($commandBus, ['test-case', 'test-target', 'other_machine']); //Add second command bus to local workflow engine to forward StartSubProcess command to message dispatcher $this->otherMachineMessageDispatcher = new InMemoryRemoteMessageDispatcher($commandBus, new EventBus()); $parentNodeCommandBus = new CommandBus(); $parentCommandRouter = new CommandRouter(); $parentCommandRouter->route(StartSubProcess::MSG_NAME)->to($this->otherMachineMessageDispatcher); $parentNodeCommandBus->utilize($parentCommandRouter); $parentNodeCommandBus->utilize(new ForwardToRemoteMessageDispatcherStrategy(new FromProcessingMessageTranslator())); $this->workflowEngine->registerCommandBus($parentNodeCommandBus, ['other_machine']); $this->getOtherMachineWorkflowProcessor(); //Add event buses to handle SubProcessFinished event $parentNodeEventBus = new EventBus(); $parentNodeEventRouter = new EventRouter(); $parentNodeEventBus->utilize(new SingleTargetMessageRouter($this->getTestWorkflowProcessor())); $parentNodeEventBus->utilize(new ToProcessingMessageTranslator()); $parentNodeEventBus->utilize(new WorkflowProcessorInvokeStrategy()); $otherMachineEventBus = new EventBus(); $toParentNodeMessageDispatcher = new InMemoryRemoteMessageDispatcher(new CommandBus(), $parentNodeEventBus); $otherMachineEventBus->utilize(new SingleTargetMessageRouter($toParentNodeMessageDispatcher)); $otherMachineEventBus->utilize(new ForwardToRemoteMessageDispatcherStrategy(new FromProcessingMessageTranslator())); $this->otherMachineWorkflowEngine->registerEventBus($otherMachineEventBus, [Definition::DEFAULT_NODE_NAME]); }