configure code
states
.withStates()
.initial(OrderState.Create)
.state(OrderState.Create, startAction)
.state(OrderState.Payed, paymentAction)
.states(EnumSet.allOf(OrderState.class));
run code
stateMachine
.getStateMachineAccessor()
.doWithAllRegions(access -> {
access.resetStateMachine(new DefaultStateMachineContext<> (OrderState.Payed, null, null, null, null));
});
stateMachine.start();
paymentAction not trigger when start,
how to trigger
Well, your code never enters state Payed which would run paymentAction. It only goes to initial state Create. Thought you didn't show any transition configs so only way it would enter that state if there is an anonymous transition between Create and Payed.
Related
I have a firstRun dialog defined in the bot like this :
// First run dialog
bot.dialog('firstRun', [
function (session, next) {
session.userData.token = _.get(session, 'message.user.token', null) || _.get(session, 'userData.token', null)
}
]).triggerAction({
onFindAction: function (context, callback) {
var score = 0;
if (session.userData.token doesn't exist or new token recieved in `session.user.message.token`){
score = 1.1;
}
callback(null, score);
}
});
And there's a LUIS model integrated with a dialog that triggers on an intent, let's say Help :
bot.dialog('help', [
(session, args) => {
let entities = _.get(args, 'intent.entities', null);
let topic = _.get(builder.EntityRecognizer.findEntity(entities, 'topic'), 'entity', null) || _.get(args, 'option', null);
session.replaceDialog(topic);
}
])
.triggerAction({
matches: 'Help'
});
The onFindAction triggers on every message. And it triggers firstRun only on the first message when session.userData.token is not set.
Problem is, if the first message is matched to Help intent, it does not get triggered. It works from the second time, when firstRun is not triggered.
How can I ensure any matching intent triggers the corresponding dialog, irrespective of firstRun?
If there's a different way possible to achieve the same thing, please suggest.
Addition
What I am trying to accomplish is this - I have a web service auth token that I want to keep in session.userData.token that refreshes every hour. So right now I trigger onFindAction on every utterance which checks if either session.userData.token doesn't exist (which means its the first utterance) OR a new token has been sent. In both cases I trigger firstRun to update session.userData.token and proceed to trigger any dialog that matched with the LUIS intent of the utterance. But whenever firstRun is triggered, none of the other dialogs are triggered. It would be ideal to have a simpler mechanism to do this i suppose.
Thanks
It sounds like you're trying to have a pass-through intent handler that would trigger before the message is routed to the actual handlers. Middleware would be the best place to handle your token refresh logic, but working with session in your middleware isn't easy. This blog post of mine explains why - http://www.pveller.com/smarter-conversations-part-4-transcript/.
Your best bet is the routing event, I believe. It's synchronous via events and you are given the session object. You should be able to validate and refresh your token as needed before the message reaches the proper intent handler destination.
bot.on('routing', function (session) {
if (!session.userData.token) {
// receive new token
}
});
Unlike middleware though, you are not given the next callback to continue the chain, so you will have to make sure you fetch the token synchronously. The blog post I mentioned previously explains this part as well.
I have a MassTransitStateMachine that orchestrates a process which involves creating multiple events.
Once all of the events are done, I want the state to transition to a 'clean up' phase.
Here is the relevant state declaration and filter function:
During(ImportingData,
When(DataImported)
// When we get a data imported event, mark this source as done.
.Then(MarkImportCompletedForLocation),
When(DataImported, IsAllDataImported)
// Once all are done, we can transition to cleaning up...
.Then(CleanUpSources)
.TransitionTo(CleaningUp)
);
...snip...
private static bool IsAllDataImported(EventContext<DataImportSagaState, DataImportMappingCompletedEvent> ctx)
{
return ctx.Instance.Locations.Values.All(x => x);
}
So while the state is ImportingData, I expect to receive multiple DataImported events. Each event marks its location as done so that that IsAllDataImported method can determine if we should transition to the next state.
However, if the last two DataImported events arrive at the same time, the handler for transitioning to the CleaningUp phase fires twice, and I end up trying to perform the clean up twice.
I could solve this in my own code, but I was expecting the state machine to manage this. Am I doing something wrong, or do I just need to handle the contention myself?
The solution proposed by Chris won't work in my situation because I have multiple events of the same type arriving. I need to transition only when all of those events have arrived. The CompositeEvent construct doesn't work for this use case.
My solution to this was to raise a new AllDataImported event during the MarkImportCompletedForLocation method. This method now handles determining whether all sub-imports are complete in a thread safe way.
So my state machine definition is:
During(ImportingData,
When(DataImported)
// When we get a data imported event, mark the URI in the locations list as done.
.Then(MarkImportCompletedForLocation),
When(AllDataImported)
// Once all are done, we can transition to cleaning up...
.TransitionTo(CleaningUp)
.Then(CleanUpSources)
);
The IsAllDataImported method is no longer needed as a filter.
The saga state has a Locations property:
public Dictionary<Uri, bool> Locations { get; set; }
And the MarkImportCompletedForLocation method is defined as follows:
private void MarkImportCompletedForLocation(BehaviorContext<DataImportSagaState, DataImportedEvent> ctx)
{
lock (ctx.Instance.Locations)
{
ctx.Instance.Locations[ctx.Data.ImportSource] = true;
if (ctx.Instance.Locations.Values.All(x => x))
{
var allDataImported = new AllDataImportedEvent {CorrelationId = ctx.Instance.CorrelationId};
this.CreateEventLift(AllDataImported).Raise(ctx.Instance, allDataImported);
}
}
}
(I've just written this so that I understand how the general flow will work; I recognise that the MarkImportCompletedForLocation method needs to be more defensive by verifying that keys exist in the dictionary.)
You can use a composite event to accumulate multiple events into a subsequent event that fires when the dependent events have fired. This is defined using:
CompositeEvent(() => AllDataImported, x => x.ImportStatus, DataImported, MoreDataImported);
During(ImportingData,
When(DataImported)
.Then(context => { do something with data }),
When(MoreDataImported)
.Then(context => { do smoething with more data}),
When(AllDataImported)
.Then(context => { okay, have all data now}));
Then, in your state machine state instance:
class DataImportSagaState :
SagaStateMachineInstance
{
public int ImportStatus { get; set; }
}
This should address the problem you are trying to solve, so give it a shot. Note that event order doesn't matter, they can arrive in any order as the state of which events have been received is in the ImportStatus property of the instance.
The data of the individual events is not saved, so you'll need to capture that into the state instance yourself using .Then() methods.
I'm trying to subscribe on upcoming events using function EvtSubscribe:
hsubscription = microsoft_EvtSubscribe(
NULL, // session
NULL, // signal
NULL, // channel path
L"<QueryList><Query Id="0" Path='Application'><Select>*[System[EventRecordID >= 1037374]]</Select></Query></QueryList>" // query
NULL, // bookmark
context, // context
clbk, // callback
EvtSubscribeToFutureEvents // flags
);
But the callback has never been called back.
I tried several approaches using XPath + channel path: Event/System[EventRecordID=1037374], *[System/EventRecordID=1037374], but it doesn't work neither.
BTW, whenever the subscription is created for any other field (like: *[System/Computer="windows-build"]) everything works perfectly fine.
What am I doing wrong?
Thanks
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new to DDD and have a concern about the size of my Aggregate Root. The object graph is like the image below. (They are collections). The problem is all of the entities depend on the state of the AggregateRoot (Event). My question is: how do I break the aggregate into smaller aggregates? It's like I have a "God" like aggregate root that just manages everything.
This is very simplistic view of my domain:
and these are the rules:
An event has a number of different states. (implemented state design
pattern here).
An event has a collection of sessions. (but only 1 can be active at a time and only if the event is in the correct state).
A session has two states: Active and Ended.
A session has a collection of Guests.
A session has a collection of photos. (Maximum
of 10).
When a session is deleted. It should delete all its children.
When a session has ended and a photo is deleted it should
check to see if there are any other photos that belong to the
session. If not it should also delete the session.
When a session has ended and a photo is deleted sometimes it should throw an exception depending on the state of the event.
When a session is active and a photo is deleted. It should not worry about whether or not the session has any other photos or not.
When a session ends it must have at least 1 photo and at least 1 guest.
A photo can be updated but only if the event is in the right state.
When an event is deleted it should delete all its children.
Edit: I have divided the 1 aggregate into smaller aggregates so that Event, Session and Photo are all ARs. The issues is a session needs to perform a check on the Event AR before starting. Is it perfectly ok to inject an event object into the sessions start method Session.Start(Event #event) or will I have concurrency issues as outlined in some of the comments?
As a first step, the following 3 articles will be invaluable: http://dddcommunity.org/library/vernon_2011/
With DDD you are splitting the entities up in to boundaries where the state is valid after a single operation from an external source completes (i.e. a method call).
Think in terms of the business problem you are trying to solve - you have used the word delete a lot...
Does delete even have a place in the wording of the business experts for whom you are designing the system? Thinking in terms of the real world and not database infrastructure, unless you can create a time machine to travel back in time and stop an event from starting and therefore change history, the word delete has no real world analogy.
If you are forcing yourself to delete children on delete, that means that operation would need to become a transaction so things that may not make sense to sit inside the aggregate root are forced too (so that the state of the entity and all its children can be controlled and assured to be valid once the method call completes). Yes there are things where you can do with a transaction across multiple aggregate roots, but these are very rare situations and to be avoided if possible.
Eventual consistency is used as an alternative to transactions and reduce complexity, if you speak to the person for whom the system is being designed, you will probably find that a delay of seconds or minutes is more than acceptable. This is plenty of time to fire off an event, to which some other business logic is listening and takes necessary action. Using eventual consistency removes the headaches that come with transactions.
Photos could take up a lot of storage yes, so you would probably need a cleanup mechanism that runs after an event is marked as finished. I would probably fire off an event once the session is marked closed, a different system somewhere else would listen for this event and after 1 year (or whatever makes sense for you) remove this from a server... assuming you used an array of string[10] for your URLs.
If this is the maximum extent of your business logic, then don't only focus on DDD, it seems like this could be a good fit for Entity Framework which is essentially CRUD and has cascade deletes built in.
Edits answer
What is a photo, does it contain attributes? Is it not instead something like a Url to a photo, or a path to a picture file?
I'm not yet thinking of databases, that should be the very last thing that is thought of and the solution should be database/technology agnostic. I see the rules as:
An event has many sessions.
A Session has the following states: NotStarted, Started and Ended.
A Session has a collection of Guests, I'm going to assume these are unique (in that two guests with the same name are not the same, so a guest should be an aggregate root).
An Event has one active Session.
When there are no active Sessions, an Event can be marked as Finished.
No Sessions can be started once an Event is marked as Finished.
A session has a collection of up to 10 photos.
When a session has ended, a photo cannot be removed.
A Session can not start if there are no Guests A Session can not end if there are no Photos.
You cannot return the Session directly, as a user of your code may call Start() on the session, you will need someway of checking with the Event that this cannot be started, so you can chain up to the root this is why I pass in the event to the Session. If you don't like this way, then just put the methods that manipulate the Session on the Event (so everything is accessed via the Event, which is enforcing all the rules).
In the simplest case, I see the photo as a string (value object) in the Session entity. As a first stab I would do something like this:
// untested, do not know if will compile!
public class Event
{
List<Session> sessions = new List<Session>();
bool isEventClosed = false;
EventId NewSession(string description, string speaker)
{
if(isEventClosed==true)
throw new InvalidOperationException("cannot add session to closed event");
// create a new session, what will you use for identity, string, guid etc
var sessionId = new SessionId(); // in this case autogenerate a guid inside this class
this.sessions.Add(new Session(sessionId, description, speaker));
}
Session GetSession(EventId id)
{
reutrn this.sessions.FirstOrDefault(x => x.id == id);
}
bool CanStartSession(Session session)
{
// TO DO: do a check session is in our array!!
if(this.isEventClosed == true)
return false;
foreach(var session in sessions)
{
if(session.IsStarted()==true)
return false;
}
return true;
}
}
public class Session
{
List<GuestId> guests = new List<GuestId>(); // list of guests
List<string> photoUrls = new List<string>(); // strings to photo urls
readonly SessionId id;
DateTime started = null;
DateTime ended = null;
readonly Event parentEvent;
public Session(Event parent, SessionId id, string description, string speaker)
{
this.id = id;
this.parentEvent = parent;
// store all the other params
}
void AddGuest(GuestId guestId)
{
this.guests.Add(guestId);
}
void RemoveGuest(GuestId guestId)
{
if(this.IsEnded())
throw new InvalidOperationException("cannot remove guest after event has ended");
}
void AddPhoto(string url)
{
if(this.photos.Count>10)
throw new InvalidOperationException("cannot add more than 10 photos");
this.photos.Add(url);
}
void Start()
{
if(this.guests.Count == 0)
throw new InvalidOperationException("cant start session without guests");
if(CanBeStarted())
throw new InvalidOperationException("already started");
if(this.parentEvent.CanStartSession()==false)
throw new InvalidOperationException("another session at our event is already underway or the event is closed");
this.started = DateTime.UtcNow;
}
void End()
{
if(IsEnded()==true)
throw new InvalidOperationException("session already ended");
if(this.photos.length==0)
throw new InvalidOperationException("cant end session without photos");
this.ended = DateTime.UtcNow;
// can raise event here that session has ended, see mediator/event-hander pattern
}
bool CanBeStarted()
{
return (IsStarted()==false && IsEnded()==false);
}
bool IsStarted()
{
return this.started!=null;
}
bool IsEnded()
{
return this.ended!=null;
}
}
No warranty on the above, and may well need to change over time as the understanding evolves and as you see better ways to re-factor the code.
A guest cannot be removed once a session has ended - this logic has been added with a simple test.
Talk about deletion of guests and leaving sessions with 0 guests - you have stated that guests cannot be removed once an event has ended... by allowing that to happen at any point would be in violation of that business rule, so it can't ever happen, ever. Besides, using the term to delete a person in your problem space makes no sense as people cannot be deleted, they existed and will always have a record that they existed. This database term delete belongs in the database, not in this domain model as you have described it.
Is this.parentEvent.CanStartSession()==false safe? No it is not multithread safe, but commands would be ran independently, perhaps in parallel, each in their own thread:
void HandleStartSessionCommand(EventId eventId, SessionId sessionId)
{
// repositories etc, have been provided in constructor
var event = repository.GetById(eventId);
var session = event.GetSession(sessionId);
session.Start();
repository.Save(session);
}
If we were using event sourcing then inside the repository it is writing the stream of changed events in a transaction, and the aggregate root's current version is used so we can detect any changes. So in terms of event sourcing, a change to the Session would indeed be a change to its parent aggregate root, since it doesn't make sense to refer to a Session event in its own right (it will always be a Event event, it cannot exist independently). Obviously the code I have given in my example is not event sourced but could be written as so.
If event sourcing is not used then depending on the transaction implementation, you could wrap the command handler in a transaction as a cross cutting concern:
public TransactionalCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand>
{
private ICommandHandler<TCommand> decoratedHandler;
public TransactionalCommandHandlerDecorator(
ICommandHandler<TCommand> decoratedHandler)
{
this.decoratedHandler = decoratedHandler;
}
public void Handle(TCommand command)
{
using (var scope = new TransactionScope())
{
this.decoratedHandler.Handle(command);
scope.Complete();
}
}
}
In short, we are using the infrastructure implementation to provide concurrency safety.
I'm prototyping some simple audit logging functionality. I have a mid sized entity model (~50 entities) and I'd like to implement audit logging on about 5 or 6. Ultimately I'd like to get this working on Inserts & Deletes as well, but for now I'm just focusing on the updates.
The problem is, when I do session.Save (or SaveOrUpdate) to my auditLog table from within the EventListener, the original object is persisted (updated) correctly, but my AuditLog object never gets inserted.
I think it's a problem with both the Pre and Post event listeners being called to late in the NHibernate save life cycle for the session to still be used.
//in my ISessionFactory Build method
nHibernateConfiguration.EventListeners.PreUpdateEventListeners =
new IPreUpdateEventListener[]{new AuditLogListener()};
//in my AuditLogListener
public class AuditLogListener : IPreUpdateEventListener
{
public bool OnPreUpdate(PreUpdateEvent #event)
{
string message = //code to look at #event.Entity & build message - this works
if (!string.IsNullOrEmpty(message))
AuditLogHelper.Log(message, #event.Session); //Session is an IEventSource
return false; //Don't veto the change
}
}
//In my helper
public static void Log(string message, IEventSource session)
{
var user = session.QueryOver<User>()
.Where(x => x.Name == "John")
.SingleOrDefault();
//have confirmed a valid user is found
var logItem = new AdministrationAuditLog
{
LogDate = DateTime.Now,
Message = message,
User = user
};
(session as ISession).SaveOrUpdate(logItem);
}
When it hits the session.SaveOrUpdate() in the last method, no errors occur. No exceptions are thrown. it seems to succeed and moves on. But nothing happens. The audit log entry never appears in the database.
The only way I've been able to get this to work it to create a completely new Session & Transaction inside this method, but this isn't really ideal, as the code proceeds back out of the listener method, hits the session.Transaction.Commit() in my main app, and if that transaction fails, then I've got an orphaned log message in my audit table for somethign that never happened.
Any pointers where I might be going wrong ?
EDIT
I've also tried to SaveOrUpdate the LogItem using a child session from the events based on some comments in this thread. http://ayende.com/blog/3987/nhibernate-ipreupdateeventlistener-ipreinserteventlistener
var childSession = session.GetSession(EntityMode.Poco);
var logItem = new AdministrationAuditLog
{
LogDate = DateTime.Now,
Message = message,
User = databaseLogin.User
};
childSession.SaveOrUpdate(logItem);
Still nothing appears in my Log table in the db. No errors or exceptions.
You need to create a child session, currentSession.GetSession(EntityMode.Poco), in your OnPreUpdate method and use this in your log method. Depending on your flushmode setting, you might need to flush the child session as well.
Also, any particular reason you want to roll out your own solution? FYI, NHibernate Envers is now a pretty mature library.