Let's say I have a task management application that uses the CQRS paradigm. How would I apply it to the following:
Scenario: As a user I want to create a task.
Java Pseudo Code:
interface Command {}
class CreateTaskCommand implements Command {
public String taskId;
public String description;
public boolean complete;
}
interface CommandHandler<Command> {
public void execute(Command command);
}
class CreateTaskHandler implements CommandHandler<CreateTaskCommand> {
public void execute(CreateTaskCommand cmd) {
validateTask(cmd);
repository.storeTask(new Task(cmd.taskId, cmd.description, cmd.complete));
}
}
Given the above code, where does the Event, EventHandler and Aggregate Root come into play (how would I proceed for the given story)?
Thanks for your help.
A command handler typically delegates behavior to an aggregate root which it loads with a repository. In turn, an aggregate root raises an event in response to the invoked action, such as TaskCreatedEvent. There are various flavors of event handlers. You can have an event handler who's sole job is to dispatch published events to external systems. External systems will subscribe to published events with an event handler which will typically invoke a command in response to the event. An event handler can also be used to invoke additional domain logic in response to the event within the local context.
Related
I have created a custom scheduled task. I have registered it as well using the following tutorial:
https://developer.shopware.com/docs/guides/plugins/plugins/plugin-fundamentals/add-scheduled-task#overview
However, in my database, the status of this task is still "queued" instead of "scheduled". This stops the task from executing. How to fix this? I am currently working on localhost.
Status queued means that a message to execute that task was dispatched to the message queue. If the status does not change automatically that indicates that now worker executed the messages from the queue.
By default (for dev setups!) there is a AdminWorker, which will poll and execute messages from the queue as long as the shopware administration is open in a browser. You can also start a worker manually per CLI:
bin/console messenger:consume
You can find more information how to work with the message queue and how to start workers in the official docs.
I had exactly the same problem.
After I had created and registered my task, it was displayed in the database as "queued" and accordingly not executed.
By manually changing it to "scheduled" it was then executed once and set back to "queued".
Of course unusable for productive use.
My error was the following:
In the services.xml I had passed additional parameters for my handler.
Accordingly my handler had a __construct() method.
However, the class inherits from "ScheduledTaskHandler" which in turn also has a constructor and expects the parameter "scheduledTaskRepository".
This repository is used to update the status.
The solution:
inject the service scheduled_task.repository in the services.xml into your custom handler
call in the construct method of the handler: parent::__construct($scheduledTaskRepository);.
In the end it should like this:
<?php declare(strict_types=1);
class myCustomHandler extends ScheduledTaskHandler
{
public function __construct(
EntityRepository $scheduledTaskRepository,
[...]
) {
parent::__construct($scheduledTaskRepository);
[...]
}
public static function getHandledMessages(): iterable
{
return [ MyCustomTask::class ];
}
public function run(): void
{
file_put_contents('test.txt', 'test');
}
}
Within an Vaadin application I am planning to implement an asynchronous result-overview for a method.
The result overview contains a table for possible results. These results should generate while a backend-method is running asynchronous in a thread. Communication between the backend and frontend of the application is planned with using CDI-Events (information for the result will be in the CDI-Event).
I already achieved to fire CDI-Events, put them into the result-table and display the table after the method is finished. But when I execute the method within a thread (so the view is displayed and events get inserted instead of waiting to see the complete table), my CDI-Events won't fire (or get received).
Is there any way to work this out? I read about receiving CDI-Events asynchronous (blog entry), but I did not find anything about firing events within a thread...
WildFly 10.0.1.Final, Java 8, Java-EE 7 and Vaadin 7.6.6.
Thread, which should fire CDI-Events:
public class Executer implements Runnable{
#Override
public void run(){
// Here will be the backend-method invocation for firing CDI-Events
// CDI-Dummy-Event - Does not fire properly. receiveStatusEvent() does not invoke
BeanManager beanManager = CDI.current().getBeanManager();
beanManager.fireEvent(new ResultEvent("Result event example"));
}
}
Bean which receives CDI-Events
public class EventReceiver implements LoggingProvider{
public EventReceiver(){
}
public void receiveStatusEvent(#Observes ResultEvent event) {
this.info("Event received: " + event.toString());
}
}
Starting the thread with help from ManagedExecutorService
public void executeAsynchBackendMethod(){
// CDI-Dummy-Event works - receiveStatusEvent() invokes correctly
BeanManager beanManager = CDI.current().getBeanManager();
beanManager.fireEvent(new ResultEvent("Result event example"));
/* The following alternative starts a thread, but the events, which are fired in the run() method, do not take any action in the receiveStatusEvent() method */
// Getting managedExecuterService
this.managedExecuterService = (ManagedExecutorService) new InitialContext().lookup("java:comp/DefaultManagedExecutorService");
// Getting Instance of executer-Runnable (for injecting the backend-service afterwards)
Instance<Executer> executerInstance = CDI.current().select(Executer.class);
Executer executer = executerInstance.get();
// Start thread
this.managedExecuterService.submit(executer);
}
In CDI 1.2 and below, events are strictly synchronous. In CDI 2.0 there is already an implemented version of asynchronous events (in Weld) but I suppose you are stuck with 1.2.
That means (as the blog post you read suggests), you can make use of the infamous EJBs.
As for why CDI does not work in this case - I would say this is all thread-bound. In other words in that given thread where you fire the event you have no observer to be triggered.
I have written an Event Sourced Aggregate and now implemented an Event Sourced Saga... I have noticed the two are similair and created an event sourced object as a base class from which both derive.
I have seen one demo here http://blog.jonathanoliver.com/cqrs-sagas-with-event-sourcing-part-ii-of-ii/ but feel there may be an issue as Commands could be lost in the event of a process crash as the sending of commands is outside the write transaction?
public void Save(ISaga saga)
{
var events = saga.GetUncommittedEvents();
eventStore.Write(new UncommittedEventStream
{
Id = saga.Id,
Type = saga.GetType(),
Events = events,
ExpectedVersion = saga.Version - events.Count
});
foreach (var message in saga.GetUndispatchedMessages())
bus.Send(message); // can be done in different ways
saga.ClearUncommittedEvents();
saga.ClearUndispatchedMessages();
}
Instead I am using Greg Young's EventStore and when I save an EventSourcedObject (either an aggregate or a saga) the sequence is as follows:
Repository gets list of new MutatingEvents.
Writes them to stream.
EventStore fires off new events when streams are written to and committed to the stream.
We listen for the events from the EventStore and handle them in EventHandlers.
I am implementing the two aspects of a saga:
To take in events, which may transition state, which in turn may emit commands.
To have an alarm where at some point in the future (via an external timer service) we can be called back).
Questions
As I understand event handlers should not emit commands (what happens if the command fails?) - but am I OK with the above since the Saga is the actual thing controlling the creation of commands (in reaction to events) via this event proxy, and any failure of Command sending can be handled externally (in the external EventHandler that deals with CommandEmittedFromSaga and resends if the command fails)?
Or do I forget wrapping events and store native Commands and Events in the same stream (intermixed with a base class Message - the Saga would consume both Commands and Events, an Aggregate would only consume Events)?
Any other reference material on the net for implementation of event sourced Sagas? Anything I can sanity check my ideas against?
Some background code is below.
Saga issues a command to Run (wrapped in a CommandEmittedFromSaga event)
Command below is wrapped inside event:
public class CommandEmittedFromSaga : Event
{
public readonly Command Command;
public readonly Identity SagaIdentity;
public readonly Type SagaType;
public CommandEmittedFromSaga(Identity sagaIdentity, Type sagaType, Command command)
{
Command = command;
SagaType = sagaType;
SagaIdentity = sagaIdentity;
}
}
Saga requests a callback at some point in future (AlarmRequestedBySaga event)
Alarm callback request is wrapped onside an event, and will fire back and event to the Saga on or after the requested time:
public class AlarmRequestedBySaga : Event
{
public readonly Event Event;
public readonly DateTime FireOn;
public readonly Identity Identity;
public readonly Type SagaType;
public AlarmRequestedBySaga(Identity identity, Type sagaType, Event #event, DateTime fireOn)
{
Identity = identity;
SagaType = sagaType;
Event = #event;
FireOn = fireOn;
}
}
Alternatively I can store both Commands and Events in the same stream of base type Message
public abstract class EventSourcedSaga
{
protected EventSourcedSaga() { }
protected EventSourcedSaga(Identity id, IEnumerable<Message> messages)
{
Identity = id;
if (messages == null) throw new ArgumentNullException(nameof(messages));
var count = 0;
foreach (var message in messages)
{
var ev = message as Event;
var command = message as Command;
if(ev != null) Transition(ev);
else if(command != null) _messages.Add(command);
else throw new Exception($"Unsupported message type {message.GetType()}");
count++;
}
if (count == 0)
throw new ArgumentException("No messages provided");
// All we need to know is the original number of events this
// entity has had applied at time of construction.
_unmutatedVersion = count;
_constructing = false;
}
readonly IEventDispatchStrategy _dispatcher = new EventDispatchByReflectionStrategy("When");
readonly List<Message> _messages = new List<Message>();
readonly int _unmutatedVersion;
private readonly bool _constructing = true;
public readonly Identity Identity;
public IList<Message> GetMessages()
{
return _messages.ToArray();
}
public void Transition(Event e)
{
_messages.Add(e);
_dispatcher.Dispatch(this, e);
}
protected void SendCommand(Command c)
{
// Don't add a command whilst we are in the constructor. Message
// state transition during construction must not generate new
// commands, as those command will already be in the message list.
if (_constructing) return;
_messages.Add(c);
}
public int UnmutatedVersion() => _unmutatedVersion;
}
I believe the first two questions are the result of a wrong understanding of Process Managers (aka Sagas, see note on terminology at bottom).
Shift your thinking
It seems like you are trying to model it (as I once did) as an inverse aggregate. The problem with that: the "social contract" of an aggregate is that its inputs (commands) can change over time (because systems must be able to change over time), but its outputs (events) cannot. Once written, events are a matter of history and the system must always be able to handle them. With that condition in place, an aggregate can be reliably loaded from an immutable event stream.
If you try to just reverse the inputs and outputs as a process manager implementation, it's output cannot be a matter of record because commands can be deprecated and removed from the system over time. When you try to load a stream with a removed command, it will crash. Therefore a process manager modeled as an inverse aggregate could not be reliably reloaded from an immutable message stream. (Well I'm sure you could devise a way... but is it wise?)
So let's think about implementing a Process Manager by looking at what it replaces. Take for example an employee who manages a process like order fulfillment. The first thing you do for this user is setup a view in the UI for them to look at. The second thing you do is to make buttons in the UI for the user to perform actions in response to what they see on the view. Ex. "This row has PaymentFailed, so I click CancelOrder. This row has PaymentSucceeded and OrderItemOutOfStock, so I click ChangeToBackOrder. This order is Pending and 1 day old, so I click FlagOrderForReview"... and so forth. Once the decision process is well-defined and starts requiring too much of the user's time, you are tasked to automate this process. To automate it, everything else can stay the same (the view, even some of the UI so you can check on it), but the user has changed to be a piece of code.
"Go away or I will replace you with a very small shell script."
The process manager code now periodically reads the view and may issue commands if certain data conditions are present. Essentially, the simplest version of a Process Manager is some code that runs on a timer (e.g. every hour) and depends on particular view(s). That's the place where I would start... with stuff you already have (views/view updaters) and minimal additions (code that runs periodically). Even if you decide later that you need different capability for certain use cases, "Future You" will have a better idea of the specific shortcomings that need addressing.
And this is a great place to remind you of Gall's law and probably also YAGNI.
Any other reference material on the net for implementation of event sourced Sagas? Anything I can sanity check my ideas against?
Good material is hard to find as these concepts have very malleable implementations, and there are diverse examples, many of which are over-engineered for general purposes. However, here are some references that I have used in the answer.
DDD - Evolving Business Processes
DDD/CQRS Google Group (lots of reading material)
Note that the term Saga has a different implication than a Process Manager. A common saga implementation is basically a routing slip with each step and its corresponding failure compensation included on the slip. This depends on each receiver of the routing slip performing what is specified on the routing slip and successfully passing it on to the next hop or performing the failure compensation and routing backward. This may be a bit too optimistic when dealing with multiple systems managed by different groups, so process managers are often used instead. See this SO question for more information.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Difference between events and delegates and its respective applications
Hi,
I am kind of new here,
I wanted to know what is the difference between Delegates & Event usages?
How can I choose which one to use?
Thanks!
If you are writing a class that exposes events, there is a subtle difference between using the event keyword or not.
For example the following code is valid and will allow clients to subscribe to either ExposedAsEvent or ExposedAsDelegate:
public delegate void ExposedEventHandler(object sender, EventArgs e);
public MyClass{
public event ExposedEventHandler ExposedAsEvent;
public ExposedEventHandler ExposedAsDelegate;
}
The only difference is that using the event modifier restricts what clients can do with the delegate. In this case clients cannot invoke the delegate directly or set it to null.
Remove the event prefix and the delegate can still be used similar to an event, however it can also be possibly 'misued' by clients.
The event modifier is really just a way of further clarifying the intent to clients of your class and limiting access (encapsulation).
Delegates are used for events in C#. A delegate is a signature for a method that can be called by an Event. An example would be:
public delegate void MessageHandler(string message);
an event that uses that delegate would be:
public event MessageHandler NewMessage;
to call the event:
NewMessage("Hello events");
which would call a method using the delegate above such as:
public void Client_NewMessage(string message)
{
MyTextBox.Text += message;
}
To subscribe to the event (using a local method implementing the delegate):
Client cl = new Client();
cl.NewMessage += new MessageHandler(Client_NewMessage);
From MSDN:
Event:
An event is a message sent by an
object to signal the occurrence of an
action
Delegate:
A delegate is a class that can hold a
reference to a method
In respect to event handling, the question is not really whether to use the one or the other. The class defines an event which is executed when some action takes place, and the consumer assigns a method which matches the delegate definition of the event.
On .NET Framework 2.0 AutoResetEvent and ManualResetEvent inherit from EventWaitHandle. The EventWaitHandle class has 4 different constructors. 3 of the constructors support giving a name to the event. On the other hand both ManualResetEvent and AutoResetEvent do not support naming and provide a single constructor that receives the initialState. I can simply inherit from EventWaitHandle and write my own implementation of those classes that support all the constructor overloads, but I don't like to re-invent the wheel if I do not have to. My questions are:
Is there a special problem in naming events?
Do you have any idea why Microsoft did not support it?
Do you have a proposal better than inheriting from the EventWaitHandle class and calling the appropriate constructor as in the following example?
public class MyAutoResetEvent: EventWaitHandle
{
public MyAutoResetEvent(bool initialState)
: base(initialState, EventResetMode.AutoReset)
{
}
public MyAutoResetEvent(bool initialState, string name)
: base(initialState, EventResetMode.AutoReset, name)
{
}
public MyAutoResetEvent(bool initialState, string name, out bool createdNew)
: base(initialState, EventResetMode.AutoReset, name, out createdNew)
{
}
public MyAutoResetEvent(bool initialState, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
: base(initialState, EventResetMode.AutoReset, string.Empty, out createdNew, eventSecurity)
{
}
}
You can make a named manual reset event like so:
// Open the event by name.
EventWaitHandle namedMRSE =
new EventWaitHandle(false, EventResetMode.ManualReset, #"TheName");
Here is the reference for the above code. I don't know of the particular reason behind the design, but there are some notes on msdn that suggest there is a distinction based on the application domain and the process:
Event wait handles are useful in many
of the same synchronization scenarios
as the Monitor class. Event wait
handles are often easier to use than
the System.Threading.Monitor.Wait and
System.Threading.Monitor.Pulse(System.Object)
methods, and they offer more control
over signaling. Named event wait
handles can also be used to
synchronize activities across
application domains and processes,
whereas monitors are local to an
application domain.