Newly Created & Loaded StatefulKnowledgeSession - JBPM 5 - drools

*strong text*What could be the problem if the task-completed event is not getting dispatched to the StatefulKnowledgeSession ?
For a new process-instance, I do
create a new session
register human-task local GenericHTWorkItemHandler
register custom event listeners
call startProcess(processDefinitionId,parameters);
It starts a new instance, creates the first human-task via the registered human-task-handler.
When I want to complete the human-task, I do
restore the KnowledgeSession with
JPAKnowledgeService.loadStatefulKnowledgeSession(lastSessionId,kBase,null,
env);
again register human-task local GenericHTWorkItemHandler
again register custom event listeners
Then call taskService.completeTask, BUT the task-completed is not dispatched to the KnowledgeSession. And the process-flow is not happening
Should I not register the event listeners again ?
Should I not register the work-item-handlers again ?
Update 1
Exception trace:
07:52:09,618 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/workflow-console].[rsservlet]] (http--0.0.0.0-8280-15) Servlet.service() for servlet rsservlet threw exception: java.lang.IllegalStateException: EntityManager is closed
at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1158) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.drools.container.spring.beans.persistence.DroolsSpringJpaManager.getApplicationScopedPersistenceContext(DroolsSpringJpaManager.java:89) [drools-spring-5.5.0.Final.jar:5.5.0.Final]
at org.drools.persistence.SingleSessionCommandService.execute(SingleSessionCommandService.java:350) [drools-persistence-jpa-5.5.0.Final.jar:5.5.0.Final]
at org.drools.command.impl.CommandBasedStatefulKnowledgeSession.getEnvironment(CommandBasedStatefulKnowledgeSession.java:478) [drools-core-5.5.0.Final.jar:5.5.0.Final]
at org.jbpm.process.workitem.wsht.GenericHTWorkItemHandler$TaskCompletedHandler.handleCompletedTask(GenericHTWorkItemHandler.java:260) [jbpm-human-task-core-5.4.0.Final.jar:5.4.0.Final]
at org.jbpm.process.workitem.wsht.GenericHTWorkItemHandler$TaskCompletedHandler.execute(GenericHTWorkItemHandler.java:234) [jbpm-human-task-core-5.4.0.Final.jar:5.4.0.Final]
at org.jbpm.task.service.local.LocalTaskService$SimpleEventTransport.trigger(LocalTaskService.java:329) [jbpm-human-task-core-5.4.0.Final.jar:5.4.0.Final]
When reloading a session I am registering new HumanTaskWorkItemhandlers.It keeps on registering event handlers with the TaskService.
When I connect the workItemHandlers, they register eventHandlers with the taskService.
When will this eventHandlers get de-registered from the taskService ?

If you are using a task service, it will by default dispatch events to all listeners. So that means multiple ksessions can receive the event (but a task completion event should only be processed by one ksession). As you mentioned, using owningKSessionOnly can be used to make sure only one ksession will react to the completion event.
You can deregister the listeners of the handler by calling dispose on the handler.

Related

Vertx - Multiple failureHandlers for the same route

The question is simple: is it possible to have multiple failure handlers for one route?
router.route(HttpMethod.POST, "/test")
.handler(LoggerHandler.create())
.handler(ResponseTimeHandler.create())
.failureHandler(MyCustomFailureHandler1.create())
.failureHandler(MyCustomFailureHandler2.create());
I'm currently using vert.x version 4.0.2, and I can see that internally, every failure handler I create is added to a failureHandlers list, but when an error is thrown, the only failure handler executing is the first one specified.
From the first failure handler (MyCustomFailureHandler1.create()), you have to call RoutingContext#next()
Documentation of RoutingContext#next() states: "If next is not called for a handler then the handler should make sure it ends the response or no response will be sent".
See TestCase here: testMultipleSetFailureHandler

Timing of `postMessage` inside service worker `fetch` event handler

I have a simple service worker which, on fetch, posts a message to the client:
// main.js
navigator.serviceWorker.register("./service-worker.js");
console.log("client: addEventListener message");
navigator.serviceWorker.addEventListener("message", event => {
console.log("client: message received", event.data);
});
<script src="main.js"></script>
// service-worker.js
self.addEventListener("fetch", event => {
console.log("service worker: fetch event");
event.waitUntil(
(async () => {
const clientId =
event.resultingClientId !== ""
? event.resultingClientId
: event.clientId;
const client = await self.clients.get(clientId);
console.log("service worker: postMessage");
client.postMessage("test");
})()
);
});
When I look at the console logs, it's clear that the message event listener is registered after the message is posted by the service worker. Nonetheless, the event listener still receives the message.
I suspect this is because messages are scheduled asynchronously:
postMessage() schedules the MessageEvent to be dispatched only after all pending execution contexts have finished. For example, if postMessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the MessageEvent is dispatched.
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Notes
However, I'm not sure what this means in this specific example. For example, when the fetch event handler has ran to completion, is the client JavaScript guaranteed to have ran, and therefore the message event listener will be registered?
I have a larger app that is doing something similar to the above, but the client JavaScript is ran slightly later in the page load, so I would like to know when exactly the event listener must be registered in order to avoid race conditions and guarantee the message posted by the service worker will be received.
By default, all messages sent from a page's controlling service worker to the page (using Client.postMessage()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). It's possible to start dispatching these messages earlier by calling ServiceWorkerContainer.startMessages(), for example if you've invoked a message handler using EventTarget.addEventListener() before the page has finished loading, but want to start processing the messages right away.
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/startMessages

How to handle commands sent from saga in axon framework

Using a saga, given an event EventA, saga starts, it sends a command (or many).
How can we make sure that the command is sent successfully then actual logic in other micro-service did not throw, etc.
Let's have an example of email saga:
When a user register, we create a User Aggregate which publishes UserRegisteredEvent, a saga will be created and this saga is responsible to make sure that registration email is sent to user (email may contain a verification key, welcome message, etc).
Should we use :
commandGateway.sendAndWait with a try/catch -> does it scale?
commandGateway.send and use a deadline and use some kind of "fail event" like SendEmailFailedEvent -> requires to associate a "token" for commands so can associate the "associationProperty" with the correct saga
that sent SendRegistrationEmailCommand
commandGateway.send(...).handle(...) -> in handle can we reference eventGateway/commandGateway that were in MyEmailSaga?
If error we send an event? Or can we modify/call a method from the saga instance we had. If no error then other service have sent an event like "RegistrationEmailSentEvent" so saga will end.
use deadline because we just use "send" and do not handle the eventual error of the command which may have failed to be sent (other service is down, etc)
something else?
Or a combination of all?
How to handle errors below? (use deadline or .handle(...) or other)
Errors could be:
command has no handlers (no service up, etc)
command was handled but exception is raised in other service and no event is sent (no try/catch in other service)
command was handled, exception raised and caught, other service publish an event to notify it failed to send email (saga will receive event and do appropriate action depending on event type and data provided -> maybe email is wrong or does not exist so no need to retry)
other errors I missed?
#Saga
public class MyEmailSaga {
#Autowired
transient CommandGateway commandGateway;
#Autowired
transient EventGateway eventGateway;
#Autowired
transient SomeService someService;
String id;
SomeData state;
/** count retry times we send email so can apply logic on it */
int sendRetryCount;
#StartSaga
#SagaEventHandler(associationProperty = "id")
public void on(UserRegisteredEvent event) {
id = event.getApplicationId();
//state = event........
// what are the possibilities here?
// Can we use sendAndWait but it does not scale very well, right?
commandGateway.send(new SendRegistrationEmailCommand(...));
// Is deadline good since we do not handle the "send" of the command
}
// Use a #DeadlineHandler to retry ?
#DeadlineHandler(deadlineName = "retry_send_registration_email")
fun on() {
// resend command and re-schedule a deadline, etc
}
#EndSaga
#SagaEventHandler(associationProperty = "id")
public void on(RegistrationEmailSentEvent event) {
}
}
EDIT (after accepted answer):
Mainly two options (Sorry but kotlin code below):
First option
commandGateway.send(SendRegistrationEmailCommand(...))
.handle({ t, result ->
if (t != null) {
// send event (could be caught be the same saga eventually) or send command or both
}else{
// send event (could be caught be the same saga eventually) or send command or both
}
})
// If not use handle(...) then you can use thenApply as well
.thenApply { eventGateway.publish(SomeSuccessfulEvent(...)) }
.thenApply { commandGateway.send(SomeSuccessfulSendOnSuccessCommand) }
2nd option:
Use a deadline to make sure that saga do something if SendRegistrationEmailCommand failed and you did not receive any events on the failure (when you do not handle the command sent).
Can of course use deadline for other purposes.
When the SendRegistrationEmailCommand was received successfully, the receiver will publish an event so the saga will be notified and act on it.
Could be an RegistrationEmailSentEvent or RegistrationEmailSendFailedEvent.
Summary:
It seems that it is best to use handle() only if the command failed to be sent or receiver has thrown an unexpected exception, if so then publish an event for the saga to act on it.
In case of success, the receiver should publish the event, saga will listen for it (and eventually register a deadline just in case); Receiver may also send event to notify of error and do not throw, saga will also listen to this event.
ideally, you would use the asynchronous options to deal with errors. This would either be commandGateway.send(command) or commandGateway.send(command).thenApply(). If the failure are businesslogic related, then it may make sense to emit events on these failures. A plain gateway.send(command) then makes sense; the Saga can react on the events returned as a result. Otherwise, you will have to deal with the result of the command.
Whether you need to use sendAndWait or just send().then... depends on the activity you need to do when it fails. Unfortunately, when dealing with results asynchronously, you cannot safely modify the state of the Saga anymore. Axon may have persisted the state of the saga already, causing these changes to go lost. sendAndWait resolves that. Scalability is not often an issue, because different Sagas can be executed in parallel, depending on your processor configuration.
The Axon team is currently looking at possible APIs that would allow for safe asynchronous execution of logic in Sagas, while still keeping guarantees about thread safety and state persistence.

Keycloak - Event Listener provider not firing new realm creation event

I have implemented a custom Event Listener provider.
I'm able to receive all the events except the realm creation event (new realm creation). I would like to get the event during realm creation as well.
Is this supported by Keycloak ? If not, any other possibilities to achieve this ?
I'm using Keycloak version 4.5.0.
Thanks in Advance.
After doing some research on keycloak code, I came to conclusion that keycloak is not providing that event by default.
So I modified below files from keycloak which will help to capture Realm creation and deletion events.
Change 1 (Most Important) :
File:
keycloak/services/src/main/java/org/keycloak/services/managers/RealmManager.java
Function:
protected void setupRealmDefaults
In above function you should add your event listener to the realm during realm creation.
Set<String> eventListenerSet = new HashSet<>();
eventListenerSet.add("jboss-logging"); //This listener will be there by default
eventListenerSet.add("EVENT_LISTENER_YOU_WANT_TO_RECEIVE_EVENT");
realm.setEventsListeners(eventListenerSet);
Change 2 :
File:
keycloak/services/src/main/java/org/keycloak/services/resources/admin/RealmsAdminResource.java
Function:
public Response importRealm
In above function add below lines before returning response
Line 1: Create object for admin event
Line 2: Prepare event to trigger with appropriate event type and representation, in this case Create
AdminEventBuilder adminEvent = new AdminEventBuilder(realm, auth, session, clientConnection);
adminEvent.operation(OperationType.CREATE).resource(ResourceType.REALM).representation(StripSecretsUtils.strip(rep)).success();
Change 3 (Needed only if delete event is required)
File:
keycloak/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
Function:
public void deleteRealm
Add the below code after the First Line
AdminAuth adminAuth = auth.adminAuth();
RealmRepresentation realmRepresentation = new RealmRepresentation();
realmRepresentation.setRealm(realm.getName());
AdminEventBuilder adminEvent = new AdminEventBuilder(realm, adminAuth, session, connection);
adminEvent.operation(OperationType.DELETE).resource(ResourceType.REALM).representation(realmRepresentation).success();

Grails: Event listener never stop (with websocket plugin)

I have a problem with my listener (platform core plugin). It never stop after event (afterInsert) was triggered (Mongo standalone)
My service catch the event and use the SimpMessagingTemplate (websocket plugin) to send on topic the data (A news user registration). The data is saved, but the listener is triggered again and again.
p.s. The data not really saved, the consequent exception, rollback the transaction. But in debug mode I can see the assigned id.
#Transactional
class MessageEventService {
SimpMessagingTemplate brokerMessagingTemplate
#Listener(topic = 'afterInsert',namespace = 'gorm')
void afterInsert(User user) {
log.info("DIOBO")
brokerMessagingTemplate.convertAndSend("/topic/myEventTopic", "myEvent: User Add ${user.name}")
}
}
And at the end...
.[grails] Servlet.service() for servlet grails threw exception
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
Why happens?!?!?
Thanks!