Vert.x run blocking handler before and after other handlers - vert.x

I'm trying to write a Vert.x Web handler that could be used to hide any processing latencies from an API to prevent figuring out existence of accounts as well as other information from an API. I would like to be able to just write something like:
router
.post("/uri")
.handler(new LatencyNormalizer())
.handler(new UriHandler());
In other words, make it as easy to use as possible and as easy to integrate into existing code bases as possible. Looking at the docs for Router and RoutingContext, I see only the following method as a possible candidate for implementing this:
https://vertx.io/docs/apidocs/io/vertx/ext/web/RoutingContext.html#addHeadersEndHandler-io.vertx.core.Handler-
I could then write code like:
public void handle(RoutingContext ctx) {
long start = System.nanoTime();
ctx.addHeadersEndHandler(v -> {
public void handle(RoutingContext ctx) {
long end = System.nanoTime();
Thread.sleep(...);
});
ctx.next();
}
Of course, this doesn't work, since sleep here blocks the thread. It looks like the handlers in the addHeaderEndHandlers list maintained internally by the RoutingContext are called synchronously, so there is no way to use e.g. vertx.SetTimer() inside the addHeaderEndHandler.
In other words, does Vert.x offer any interface that allows creating a handler which is called asynchronously before writing out to the wire (and with nothing written until the async call finishes)? This is for example how Netty works under the hood, which Vert.x leverages. I know I could implement this LatencyNormalizer as a base class for my other handlers, but it would not be as easy to integrate in existing code in that case.

Related

Async tree exploration with RxJava

I'm trying to build an algorithm to explore a tree with RxJava.
My reason to use RxJava is that my node processing function is already using RxJava to send RPCs to other services. Note that the order in which the different branches of the tree are explored is not important.
Ideally, I would like to have something like a QueueFlowable<Node> extends Flowable<Node> which would expose a push function that Observers could use to add new nodes in the queue after processing them.
private static main(String[] args) {
QueueFlowable<Node> nodes = new QueueFlowable<>();
nodes.push(/* the root */);
nodes.concatMap(node -> process(node)).map(nodes::push));
nodes.blockingSubscribe();
}
// Processes the node and returns a Flowable of other nodes to process.
private static Flowable<Node> process(Node node) { ... }
This sounds like something relatively common (as I would expect web crawlers to implement something similar) but I still don't manage to make it work.
My latest attempt was to use a PublishProcessor as follows:
PublishProcessor<Mode> nodes = PublishProcessor.create();
nodes.concatMap(node -> process(node)).subscribe(nodes);
nodes.onNext(/* the root node */);
nodes.blockingSubscribe();
Of course, this never terminates as the processor does not complete.
Any help would be much appreciated!

DispatcherTimer in MVVM with Prism?

I'm working on a multi-platform MVVM app, and I want to keep the ViewModel platform-agnostic.
I need to make use of DispatcherTimer or any other timer. Since the DispatcherTimer is not part of .NET Standard/Core, I was wondering if there are better alternatives to use so I can keep the VM clean of plat-specific code (I want it to depend only on .NET Core)?
The way it works is that the ViewModel implements an interface that exposes an event that the View is listening to, and responds to it accordingly.
The timer raises this event upon each tick.
The first option would be to just use classic Timer, which does fire on a non-UI thread and then just use Dispatcher manually in the consuming view. This is however not that convenient.
Other option would be to provide an interface, that consumers of your library could implement, which would have a method like RunOnUiThread(Action action) and which you would just use to make sure the view-specific code runs on the UI thread.
The best solution would probably be to get inspiration in Prism itself. For example the EventAggregator in the library can publish events on the UI thread - it first captures the current thread's synchronization context (see here on GitHub):
var syncContext = SynchronizationContext.Current;
This must be done for example during the View model construction, on the UI thread. And then you can invoke an action on this UI synchronization context even from another thread (see here on GitHub):
syncContext.Post((o) => action(), null);
This way you could just use one of the .NET Standard Timer classes and from their callback then use the SynchronizationContext to run an action on UI thread.
The other way you should know about DispatcherTimer is sometimes we may use DispatcherTimer to do something alternately.
We can use Task.Delay to replace DispatcherTimer sometimes.
Such as we need to run the code A every 5 seconds.
public async void Foo()
{
while (true)
{
// run a every 5 seconds
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5));
A();
}
}
private void A()
{
}
And the A will run in the main thread if the main thread calls the Foo and I think you
can consider using this method in the framework.

How to write tests for tracking event flows in eventbus?

Long description:
In our gwt with mvp4g app we have pretty complicated flow of events in eventbus. One event like LOGIN produces multiple others as a reaction from presenters/handlers. Currently we have great difficulties with understanding how events interrelated i.e. which events must follow this particular one.
We have tests for presenters and views, but we are lacking tests which would clearly show/model event flows, preferably without usage of real views and services.
Short description:
New tests on eventBus(?) should be developed which should clearly describe and test event flows.
I have few rud ideas but they all sounds not satisfactory:
Write custom implementation(could be ugly) of mvp4g eventbus and:
use real presenters
use mock(?) views
mock services
verify all produced service calls
Why not cool: (a) In this case test would not verify produced events directly but only that ones which have services. (b)
EventBus implementation would look rather scarry - it must create each presenter with mocked services and views
Find a way to use some magical mvp4g mechanism to create eventBus in test and mock vies, services.
Why not cool : same as prev - only indirect verification through services is possible, and I cannot find how to create eventBus manually and solve all problems with GIN, inter GWT module dependencies and so. I guess there is no simple way to do it.
Is there any general solution for problem of tracking event tree in tests? Guess I'm not the first person to stare at complicated eventbus event flows.
Do you want to test the eventBus? Or do you want to track all event which are fired?
If you want to track your events, maybe some kind of EventMonitor could help you? A class that implements all necessary EventHandler and log every event that occurs.
Something like that? Just instance that class before your tests starts.
import java.util.logging.Logger;
import com.google.gwt.event.shared.GwtEvent;
import com.google.web.bindery.event.shared.EventBus;
public class EventMonitor implements AEventHandler, BEventHandler /* , ... */{
private static int event_count = 1;
private final Logger logger = Logger.getLogger(this.getClass().getName());
public EventMonitor(EventBus eventBus) {
eventBus.addHandler(AEvent.getType(), this);
eventBus.addHandler(BEvent.getType(), this);
// [...]
}
private void logEvent(GwtEvent<?> event) {
logger.info(event_count + " useful information");
event_count++;
}
#Override
public void onAEvent(AEvent event) {
logEvent(event);
}
#Override
public void onBEvent(BEvent event) {
logEvent(event);
}
}

Testing GWTP presenter with asynchronous calls

I'm using GWTP, adding a Contract layer to abstract the knowledge between Presenter and View, and I'm pretty satisfied of the result with GWTP.
I'm testing my presenters with Mockito.
But as time passed, I found it was hard to maintain a clean presenter with its tests.
There are some refactoring stuff I did to improve that, but I was still not satisfied.
I found the following to be the heart of the matter :
My presenters need often asynchronous call, or generally call to objects method with a callback to continue my presenter flow (they are usually nested).
For example :
this.populationManager.populate(new PopulationCallback()
{
public void onPopulate()
{
doSomeStufWithTheView(populationManager.get());
}
});
In my tests, I ended to verify the population() call of the mocked PopulationManager object. Then to create another test on the doSomeStufWithTheView() method.
But I discovered rather quickly that it was bad design : any change or refactoring ended to broke a lot of my tests, and forced me to create from start others, even though the presenter functionality did not change !
Plus I didn't test if the callback was effectively what I wanted.
So I tried to use mockito doAnswer method to do not break my presenter testing flow :
doAnswer(new Answer(){
public Object answer(InvocationOnMock invocation) throws Throwable
{
Object[] args = invocation.getArguments();
((PopulationCallback)args[0]).onPopulate();
return null;
}
}).when(this.populationManager).populate(any(PopulationCallback.class));
I factored the code for it to be less verbose (and internally less dependant to the arg position) :
doAnswer(new PopulationCallbackAnswer())
.when(this.populationManager).populate(any(PopulationCallback.class));
So while mocking the populationManager, I could still test the flow of my presenter, basically like that :
#Test
public void testSomeStuffAppends()
{
// Given
doAnswer(new PopulationCallbackAnswer())
.when(this.populationManager).populate(any(PopulationCallback.class));
// When
this.myPresenter.onReset();
// Then
verify(populationManager).populate(any(PopulationCallback.class)); // That was before
verify(this.myView).displaySomething(); // Now I can do that.
}
I am wondering if it is a good use of the doAnswer method, or if it is a code smell, and a better design can be used ?
Usually, my presenters tend to just use others object (like some Mediator Pattern) and interact with the view. I have some presenter with several hundred (~400) lines of code.
Again, is it a proof of bad design, or is it normal for a presenter to be verbose (because its using others objects) ?
Does anyone heard of some project which uses GWTP and tests its presenter cleanly ?
I hope I explained in a comprehensive way.
Thank you in advance.
PS : I'm pretty new to Stack Overflow, plus my English is still lacking, if my question needs something to be improved, please tell me.
You could use ArgumentCaptor:
Check out this blog post fore more details.
If I understood correctly you are asking about design/architecture.
This is shouldn't be counted as answer, it's just my thoughts.
If I have followed code:
public void loadEmoticonPacks() {
executor.execute(new Runnable() {
public void run() {
pack = loadFromServer();
savePackForUsageAfter();
}
});
}
I usually don't count on executor and just check that methods does concrete job by loading and saving. So the executor here is just instrument to prevent long operations in the UI thread.
If I have something like:
accountManager.setListener(this);
....
public void onAccountEvent(AccountEvent event) {
....
}
I will check first that we subscribed for events (and unsubscribed on some destroying) as well I would check that onAccountEvent does expected scenarios.
UPD1. Probably, in example 1, better would be extract method loadFromServerAndSave and check that it's not executed on UI thread as well check that it does everything as expected.
UPD2. It's better to use framework like Guava Bus for events processing.
We are using this doAnswer pattern in our presenter tests as well and usually it works just fine. One caveat though: If you test it like this you are effectively removing the asynchronous nature of the call, that is the callback is executed immediately after the server call is initiated.
This can lead to undiscovered race conditions. To check for those, you could make this a two-step process: when calling the server,the answer method only saves the callback. Then, when it is appropriate in your test, you call sometinh like flush() or onSuccess() on your answer (I would suggest making a utility class for this that can be reused in other circumstances), so that you can control when the callback for the result is really called.

Cancel GWT RequestFactory request

Is there a way to cancel/abort request factory requests? Using GWT 2.3
There is no way to cancel a request after the fire() method has been called. Consider building a custom Receiver base class such as the following:
public abstract class CancelableReceiver<V> extends Receiver<V> {
private boolean canceled;
public void cancel() {
canceled = true;
}
#Override
public final void onSuccess(V response) {
if (!canceled) {
doOnSuccess(response);
}
}
protected abstract void doOnSuccess(V response);
}
The pattern can be repeated for other methods in the Receiver type.
Another option would be to create an alternative com.google.web.bindery.requestfactory.shared.RequestTransport type, instead of using DefaultRequestTransport. Downside to this (and upside to BobV's approach) is that you won't know when in the request on the server you kill it, so it might have already run some of your methods - you won't get feedback from any of them, you'll just stop the outgoing request.
I suspect this is why RF doesn't have this feature already, as RPC does. Consider even the case of RPC though or RequestBuilder - how do those notify the server that they've changed their mind, and to not run the request? My understanding is that they don't - the only way they are shut down early is when they try to read/write to the response, and get a tcp error, as the connection has been closed. (It's possible I am mistaken, and that another thread keeps an eye on the state of the tcp connection and calls thread.stop(Throwable), but stop has been deprecated for quite a while.)
One thought would be to send a message to the server, telling it to kill off other requests from the same session - this would require active participation in your server code though, possibly made generic in a ServiceLayerDecorator subtype, probably in at least invoke, loadDomainObject(s), and getSetter, among others. This pretty clearly is to involved to ask GWT to build it for you though...