Event/Observer Driven Ruby on Rails - ruby

I have an application that lends itself to an event/listener model. Several different kinds of data get published (event), then many different things may or may not need to act on that data (listeners). There's no specific order the listeners need to happen in and each listener would determine whether or not it needs to act on the event.
What tools for Rails apps are there to accomplish this task? I'm hoping to not have to do this myself (although, I can. It's not THAT big a deal.)
Edit: Observer pattern might be a better choice for this

Check out EventMachine. It is a very popular event-processing library for Ruby. It looks quite good, and a lot of other libraries seem to take advantage of it (Cramp).
Here is a good introduction: http://rubylearning.com/blog/2010/10/01/an-introduction-to-eventmachine-and-how-to-avoid-callback-spaghetti/

You'll probably want to hook into ActiveRecord's Observer class.
http://api.rubyonrails.org/v3.2.13/classes/ActiveRecord/Observer.html
With it, your models can execute custom logic for several lifecycle events:
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
If I understand your intent correctly, all you'll need to do is call the methods that represent your listener's action to an event from those callbacks.

You may want to use ActiveSupport::Notifications.instrument.
It is a general-purpose bridge for decoupling event sending to event reacting. It's geared towards executing all listeners during a single web request, unlike EventMachine, which is geared towards having lots of concurrent things happening.

I have created a ruby gem responding exactly to this use case : event_dispatcher
This gem provides a simple observer implementation, allowing you to subscribe and listen for events in your application with a simple and effective way.

Related

Design guides for Event Sourced microservices

I am thinking what is the best way to structure your micro-services, in the past the team I was working with used Axon Framework and PostgreSQL and each microservice had its own event store in the PostgreSQL database, then we built communication between using REST.
I am thinking that it would be smarter to have all microservices talk to the same event store as we would be able to share events faster instead of rewriting the communication lines using REST.
The questions that follows from the backstory is:
What is the best practice for having an event store
Would each service have its own? Would they share the same eventstore?
Where would I find information to inspire and gather more answers? As searching the internet for best practices and how to structure the Event Store seems like searching for a needle in a haystack.
Bear in mind, the question stated is in no way aimed at Axon Framework, but more the general idea on building scalable and good code. As the applications would work with each own event store for write model and read models.
Thank you for reading and I wish you all the best
-- Me
I'd add a slightly different notion to Tore's response, although the mainline is identical to what I'm sharing here. So, I don't aim to overrule Tore, just hoping to provide additional insight.
If the (micro)services belong to the same Bounded Context, then they're allowed to "learn about each other's language."
This language thus includes the events these applications publish and store.
Whenever there's communication required between different Bounded Contexts, you'd separate the stores, as one context shouldn't be bothered by the specifics of another context.
Hence it is beneficial to deduce what services belong to which Bounded Context since that would dictate the required separation.
Axon aims to support this by allowing multiple contexts with the Axon Server, as you can read here.
It simply allows the registration of applications to specific contexts, within which it will completely separate all message streams (so commands, events, and queries) and the Event Store.
You can also set this up from scratch yourself, of course. Tore's recommendation of Kafka is what's used quite broadly for Event Streaming needs between applications. Honestly, any broadcast type of infrastructure suits event distribution, as that's how events are typically propagated.
You want to have one EventStore per service, just as you would want to have one relation database per service for a non EventSourced system.
Sharing a database/eventstore between services creates coupling and we have all learned the hard way that this is an anti-pattern today.
If you want to use a event log to share events across services, then Kafka is a popular choice.
Important to remember that you only do event-sourcing within a service bounded context.

CQRS Commands as Models for POST actions

I'm getting started with CQRS, and thought It would make the most sense to use the Command object as the Model on my forms. I can take advantage of some of the client-side validation for the commands using DataAnnotations, client-side validation, makes it pretty clean...
My question... does this raise any problems? If my command does not have a default constructor, will this make this process impossible? Do I need to create my own CommandModelBinder that can constructor inject the aggregate ID?
Your thoughts, I can't find this technique anywhere and Im assuming because it doesn't work.
I'd recommend that you take a look at Greg Young's article on task-based UI's on how DTOs and Messages interact with your system (both client-side and server-side).
I agree with Sebastian that your Commands will match exactly with what your user interface will look like. As a result, you'll probably need to have separate DTO/Model classes and Commands. That's really not a bad thing as your Model is really the result of your query-side of the system and really shouldn't be an exact duplicate of the messages you're sending into the system.
Also, by keeping your commands separate from your model, your concern about Command constructors goes away. Your controller just collects information from the client, constructs the command and then submits it.
If you're getting started with CQRS, Greg's site (cqrsinfo.com) is pretty good, especially his 6 1/2 hours video. Yes, it's 6 1/2 hours, but it really is a great introduction and overview of what CQRS is all about. It helped me out tremendously.
Hope this helps!
Using a POST to send your command to the domain command handlers seems sensible. But it's unlikely to be the exact object you bind your interface to. Commands in the interface (e.g. Mouse clicks) will become domain commands (create user). Your GUI is most likely to be bound to the results of a Query.
For the reasons you mentioned you would create View Models which are basically your dto's sent between client and server. This way you can use all the mvc goodness like modelbinding, data annotations, etc. In you controller you would then create the command and send the command to the service bus.
I think this will help you separate concerns a little better and it would be easier to test in my opinion.

event aggregator in MVVM

I'm working for a while with silverlight and MVVM (in its simplest form, it's to say hand-made), but I barely understand what is an event aggregator (and how to make an implementation of this).
What is hidding behind this name?
Can someone explain this quickly (or post a link?).
An event aggregator is generally a broker object that you can take a reference to and specify what type of events you want to receive, without having to take a reference or even be aware of the objects generating the events.
Prism's EventAggregator is the most common one. See: http://msdn.microsoft.com/en-us/library/ff649187.aspx
It describes itself as:
The EventAggregator service is
primarily a container for events that
allow decoupling of publishers and
subscribers so they can evolve
independently. This decoupling is
useful in modularized applications
because new modules can be added that
respond to events defined by the shell
or, more likely, other modules.

How to design prism EventAggregator?

Pattern of pub-sub events is that the
publisher should not know or care if
there are any subscribers out there,
nor should it care what the
subscribers do if they are there (from
Brian Noyes'
blog)
What are the best practices to using EventAggregator in Prism? Currently I have few modules which are loosely coupled and work independently. These modules use EventAggregator to communicate to other modules. As the application grows I'm confused on how to document my code. There could be many modules publishing Events and many others subscribing to it as Brian puts neither of them knows what other does exactly. When creating a new module how do I make sure they are subscribed to some XYZ event without breaking the loosely coupled structure?
How do I represent a module using EventAggregator visually (some kind of diagrams)?
You have a lot of questions in your post that can be answered "it depends on your application," but I'll try to answer some of them.
One thing that I see most often with EventAggregator is abuse. Many people use EventAggregator in a way that makes both the publisher and subscriber dependent on each other. This brings me to my first bit of advise:
Never assume there are any subscibers to an event.
EventAggregator is useful for publishing events other views might be interested in. For example, in our application we allow a user to change someone's name. This name might be displayed on other views already open in the application (we have a tabbed UI). Our use case was we wanted to have those UIs update when the name was changed, so we published a "UserDataChanged" event so that open views could subscribe and refresh their data appropriately, but if no views that were open were interested in this data, no subscribers were notified.
Favor .NET Events over EventAggregator events where appropriate
Another mistake I see frequently is a business process that is implemented using EventAggregator where data is sent to a central party and then that party replies, all using EventAggregator. This is leads to some side-effects you'd likely want to avoid.
A variation on that I see a lot is communication from a parent view to a sub-view, or vice-versa. Something like "TreeItemChecked" or "ListViewItemSelected". This is a situation where traditional .NET Events would be used, but an author decided that if they have a hammer (EventAggregator), everything (Events) looks like a nail.
You asked about modeling the EventAggregator and I would say this: the EventAggregator is only special in that it allows for decoupling and doesn't create strong references to events (avoiding memory leaks, etc). Other than that, it's really just a very slight variation of the Observer Pattern. However you are modeling Observers is how you would model the EventAggregator in whatever type of diagram you are trying to create.
As to your question about making sure some module or another is subscribed to an event: you don't. If you need to ensure there are subscribers, you should not use the EventAggregator. In these cases I would recommend a service running in your application that modules can grab from your container and use or other similar thing.
The thing to keep in mind about your modules is that you should be able to completely remove one and the rest of your application functions normally. If this is not the case, you either have a module dependency (best to be avoided, but understandable), or dependent modules should be combined into one.

Usage of observer pattern with EJB and AJAX

I want to build an Ajax gui, that is notified on any state changes happening in my ejb application. To achieve this, I thought I build an stateful ejb (3.0) that implements the Observable interface to which the Ajax client is added as an observer.
First, is this possible with Ajax. If yes, is this a good design idea or is there a more propriate way to do this?
Thanks in advance!
Cheers,
Andreas
It sounds like you are interested in 'Reverse-Ajax', where the client is notified when an event happens server side. This is different than standard Ajax, where an asynchronous event is sent to the server based on some client action. Reverse Ajax is possible, and one framework that does a very good job of allowing this is and simplifying the underlying complexity is DWR.
http://directwebremoting.org/dwr/reverse-ajax
You'll want to read up on the performance implications of the various ways to implement based on your expected load, webapp container, etc. regardless of which framework you use.
As for whether or not it is good practice, that really depends on your application. If it is important to get near-real time data pushed back to the client and you don't want to use something like Flex or other heavier frameworks, then I'd say you are on the right track. If the data does not need to be real time, or if your load is extremely high, then perhaps a more simple approach like a scheduled page refresh will save you some complexity and help with performance.
Now, some time later there is a new possible answer to your question: Usage of Websockets
From the previously linked website by Pete: "The web was not designed to allow web servers to make connections to web browsers..." That is changing now with html5.
http://en.wikipedia.org/wiki/WebSockets

Resources