Spring webFlux difference between DTOs - spring-webflux

I use Spring boot reactive web flux for my rest endpoint.
What is the difference between :
#PostMapping
public Mono someMethod(#RequestBody SomeDTO someDto){
.....
to
#PostMapping
public Mono someMethod(#RequestBody Mono<SomeDTO> someDTO) {
....
I don't understand the difference in input argument to my controller method . I know one is pojo and the other in mono but what does it mean from reactive point of view?

First things, some background. You are using the 1.4. Annotated Controllers classes for WebFlux. These implementations are based on the 1.5. Functional Endpoints classes. I would recommend using the Functional Endpoints directly.
From a reactive POV you have to understand that you need to create the reactive flow. In the Mono method this has been created for you, in the SomeDTO method you should probably use Mono.just(someDTO) to create it.
What is important to understand in that statement is creation statements will be executed during the build phase not the execution phase of the reactive. The build phase is not executed asynchronously.
So, consider two mono creation statements.
return Mono.just(Thread.sleep(1000));
and
return Mono.just(1000).map(Thread::sleep);
Yes, I know it won't compile because of interrupted exception, but in the first case the Mono won't be returned to the client until 1 second and then it will do nothing when subscribed to. In the second case the mono will be returned to the client right away and will wait one second after it is subscribed to. The second one is what you are striving for.
What does it mean to you? Consider
return Mono.just(repo.save(someDto));
and
return someDto.map(repo::save);
In the first case, as above, someDto will be saved in the repo and then the mono will be returned to the client and will do nothing when subscribed to. Wrong! In the second case the mono will be returned to the client, the thread released back to the webflux framework for use in another request, and someDto will be saved when the client subscribes to the returned mono. What you are striving for.
Do it correctly with your first case by doing
return Mono.just(someDto).map(repo::save);
This is doing Mono.just(someDto) yourself whereas in your second case the webflux framework is doing it for you.
Which to choose? If you are just going to wrap someDto in a mono and use it then might as well have the framework do it for you or use the functional endpoints. If you are going to create a mono for some other reason and then use someDto during a mapping process use your first case. This second reason is, IMHO, a rare use case.
Typically when using the functional endpoints you will end up doing request.bodyToMono(SomeDto.class) which is equivalent to your second case and what is done by the framework for you in your second case.

Related

What does it mean for Spring Reactor's Mono to return empty?

From its documentation, it states that Mono returns empty when it "completes without emitting any items". What does it mean to complete without emitting any items? Does it mean that it never sent any request or?
It depends on the implementation. Generally, for reactive data access libraries it means that the request/query was executed but yielded no results. However, this is not always the case as there are alternative behaviours like returning a default value or returning a Mono with error. Always consult the relevant library (e.g.: Spring Data) documentation to understand the behavior.
Answering from the perspective of "what does it mean in terms of behavior", not "what does the empty Mono behavior means in terms of business logic":
Mono is a Publisher, an interface that is defined to emit a set of signals to its Subscriber: onNext, onComplete, onError.
In the case of Mono the possible combinations are restricted:
onNext followed by onComplete (something was produced and we're done)
onError (something went wrong)
onComplete (nothing was produced but we're done)
The last one is the empty case you're wondering about: an empty Mono is one that never emits the onNext signal but rather simply emits onComplete.
To add to Simon's complete answer (why do I do that, hm?)
One typical use case of Mono returning empty is filtering. Think of it like if you need to do something in if then else style, in terms of Mono you could use .filter for then and .switchIfEmpty for else.
To understand the logic behind, for me it was also useful to look onto interface MonoSink<T> apidoc. It basically says the same: you can either complete without value, or with it, see two overloaded success methods.

Project Reactor. Mono.map() vs Mono.flatMap()

What is the principal difference between these in terms of Mono?
From the documentation, I read that flatMap acts asynchronous and map synchronous. But that doesn't really make sense for me b/c Mono is all about parallelism and that point isn't understandable. Can someone rephrase it in a more understandable way?
Then in the documentation for flatMap stated (https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#flatMap-java.util.function.Function-):
Transform the item emitted by this Mono asynchronously, returning the
value emitted by another Mono (possibly changing the value type).
Which another Mono is meant there?
Mono#flatMap takes a Function that transforms a value into another Mono. That Mono could represent some asynchronous processing, like an HTTP request.
On the other hand, Mono#map takes a Function that transforms a value of type T into another value, of type R. That transformation is thus done imperatively and synchronously (eg. transforming a String into an URL instance).
The other subtlety with flatMap is that the operator subscribes to the generated Mono, unlike what would happen if you passed the same Function to map.
I would say it simply,
map(a -> b) is returning Mono.just(b)
map wraps the returned value in another mono whereas flatmap already expects a Mono do no further wrapping required
Practical use case example,
public Mono<String> getResponseFromServer(Mono<String> request) {
// here few logics
request.flatMap(r -> callServer(r);
}
Where callServer looks like
public Mono<String> callServer(String body) {
// invoke http
return http call returned mono
}
Above use case is not possible with map.

SimpleRetryStrategy Failed<TMessage>

interface IHandleMessages has contravariant parameter TMessage
IHandleMessages<in TMessage>
this makes possible to Register in Ioc Container IHandleMessages<DerivedType> and have implementation in Handler : IHandleMessages<BaseType>. That is Ok.
The problem consist in Failed<TMessage> wrapper for failed Messages, where TMessage is not contravariant. That makes impossible to have
implementation of Handler like Handler : IHandleMessages<Failed<Base>>
and registration in Ioc container .As<IHandleMessages<Failed<DerivedType>>>()
I think its reasonable to have Failed<in TMessage> but not Failed<TMessage>
What do you think?
I did not consider this scenario when I implemented the second-level retries mechanism in Rebus, but I would like to support it.
I've added the feature to 0.99.36 (which will be on NuGet in a few days if the tests pass and everything else looks good).
It looks slightly different from what you proposed though, since co- and contra-variance can only be had with interfaces.
Therefore, Rebus now dispatches an IFailed<out TMessage>, because then you can implement e.g. IHandleMessages<IFailed<AbstractBaseClass>> when the failed message is DerivedFromAbstractBaseClass.
Keep an eye on NuGet.org - it'll be out in a few days :)
In the meantime you can see what the code looks like in the accompanying test.

Ninject MockingKernel with Saboteurs

Is it possible to use MockingKernel so that it generates mock objects automatically that, if interacted with, will throw an exception (a.k.a, saboteurs)?
This is useful when you want to get an object with various dependencies, but you know your code should only be interacting with some of them. If you don't explicitly Bind a dependency (via ToMock, etc.), it should return an object that throws an exception the first time it is interacted with.
This is much better than waiting until the code finishes executing, then writing a bunch of checks to make sure you didn't call into a mock.
Does this already exist?
The answer provided above did not indicate how to setup the Ninject MockingKernel using MOQ so that the default behavior is Strict. For the benefit of others, here is what I found.
The Ninject.MockingKernel.Moq namespace provides the class NinjectSettingsExtensions with the methods SetMockBehavior() and GetMockBehavior() that allow you to specify which mocking behavior to use as the global default. I have NOT been able to find any way to override the default for an individual GetMock() request.
using Ninject;
using Ninject.MockingKernel.Moq;
var kernelSettings = new NinjectSettings();
kernelSettings.SetMockBehavior(MockBehavior.Strict);
using(var kernel = new MoqMockingKernel(kernelSettings))
{
var mockFoo = kernel.GetMock<IFoo>(); // mockFoo.Behavior == MockBehavior.Strict
}
I had been using NSubstitute's implementation of MockingKernel. NSubstitute doesn't really support a "strict" mode and you can't configure it through the NSubstituteMockingKernel class.
However, you can configure Moq to do strict mode. Best of all, the MoqMockingKernel class allows you to change the mock behavior globally. This way, any calls that aren't configured result in an exception being thrown.
This is exactly what I was looking for. The only pain was switching from NSubstitute to Moq.

Profiler lib for wcf + postsharp

We need to add a new profiling feature to our WCF application, for logging where time is spendt in the application. I'm looking at PostSharp for a convention driven approach of applying the logging and need some input on how to actually log it. I've already created a custom class for logging purposes, using StopWatch and can log the steps through the layers of my WCF application. However I'm wondering if there's a thread safe alternative library I could use in conjunction with PostSharp for this purpose. I've come across MiniProfiler, but it seems to be intended for ASP.NET MVC applications mainly. Any other frameworks I should consider or should I just use my custom class?
Thanks
I did something like that in the past using a IClientMessageInspector implemented on a custom IEndpointBehavior.
Depending on what kind of logging you want, this might just do the trick. There's an example in the following link
IClientMessageInspector Interface
PostSharp itself is thread-safe. The aspects that you write may be thread-unsafe if poorly written, but there's always a way to make them thread-safe.
If you're using OnMethodBoundaryAspect and need to pass something from OnEntry to OnSuccess, store the initial stopwatch value in OnMethodExecutionArgs.MethodExecutionTag.