Blockhound is not detecting straightforward blocking code - spring-webflux

Using spring boot webflux, I'm trying Blockhound for a very simple blocking call, but it doesn't seem to be detecting it.
<dependency>
<groupId>io.projectreactor.tools</groupId>
<artifactId>blockhound</artifactId>
<version>1.0.6.RELEASE</version>
</dependency>
in main method:
public static void main(String[] args) {
BlockHound.install();
SpringApplication.run(MyApplication.class, args);
}
My blocking endpoint:
#GetMapping("/block")
public Mono<String> block() {
String a = Mono.just("block").block();
return Mono.just(a);
}
Any idea?
EDIT:
When I use UUID.randomUUID() in my endpoint, I get the error related to a blocking FileInputStream#readBytes used by randomUUID().
So I suppose My install is good

Nothing is wrong here, you've just hit a corner case.
Mono.just() is a rather special kind of Mono in more ways than one (which is why I despair at its use in so many simple "getting started" style examples, but I digress) - since you're literally just wrapping a value inside a dummy publisher, it never needs to block in order to return its value, even if you call the block method. The method name might imply you're blocking, but you can trivially verify from the source code that it just returns a value. There's therefore no blocking operation occurring, and so nothing for Blockhound to complain about.
If you were to add another operator in the mix, even if it has no real-world effect:
String a = Mono.just("block").cache().block();
...then you'll see Blockhound start complaining, as you're no longer directly using the special case of MonoJust.
Blockhound is doing exactly what it should here, the issue is that you're (very understandably) expecting something to block which doesn't.

Related

For some reason, I want to use thread.sleep in my serenity screenplay project, how can I use it?

I am already using implicit and fluent wait, but want to use thread.sleep, so want to know the syntax of it
Using Thread.sleep() is discouraged and there is no Performable for that in serenity.
Many testers pepper their web tests with Thread.sleep() statements, but this is the sub-optimal at best. It slows down the tests, makes them more brittle, and can hide genuine application issues. More insidiously, when our steps are artificially slowed by sleep statements, it takes longer not only to run and troubleshoot existing tests, but also to develop new ones.
https://johnfergusonsmart.com/handling-waits-and-asynchronous-pages-in-serenity-bdd/
I know my reply is very late and it's a very bad practice but I am posting here just for the sake of if it can be done. Also from your question it seems like you want to make a task of it. To do this you can make a anonymous task. For example
Integer wait = 500;
Task.where("{0} uses thread sleep",(actor)-> {
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
You can wrap it inside a function or assign it to a Task variable. Just if you are wandering Task class have a overloaded method named where which takes a Consumer<Actor> as second argument instead of Performable.
Also you can make a normal task class by implementing Task and use thread sleep in performAs method.
But again considering you are using serenity I doubt it will come to the point where you would have to use Thread.sleep.

DDD reusable functionality in an Entity/Aggregate

I have the following desing in DDD
Post Aggregate with
Body: HTML of the post
Banner entity with
Html: HTML of the banner
The Banner entity belongs to Post aggregate, so I want to create a method BodyWithBanners in the Post aggregate.
The point of this method will be to search into the HTML of the Post.Body and insert the HTML of the Banner.
So far, so good.
However I have intention of reuse this functionallity in abstract: "Insert some HTML inside another HTML". So I'm creating a diffent class for doing that: BannerReplacer
Here comes the problem, how should I invoke this new class?
Just create an instance inside the Post.BodyWithBanners method (breaking Dependency Injection)
Passing the BannerReplacer in the constructor of the Post aggregate (This can be a nightmare for creating Post instances)
Passing the BannerReplacer to the BodyWithBanners method (which implies the client using Post must handle the BannerReplacer)
I have chosen for now the first option, but I don't feel really confortable with it, I believe there must be a better way of doing this.
I have chosen for now the first option, but I don't feel really comfortable with it, I believe there must be a better way of doing this.
Much of the time, the first option is fine -- so you should practice being comfortable with it. That mostly means thinking more about what dependency injection is for, and having a clear picture in your mind for whether or not those forces are at play here.
If Banner is an entity, in the domain-driven-design sense, then it is probably something analogous to an in memory state machine. It's got a data structure that it manages, and some functions for changing that data structure, or answering interesting questions about that data structure, but it doesn't have I/O, database, network etc concerns.
That in turn suggests that you can run it the same way in all contexts - you don't need a bunch of substitute implementations to make it testable. You just instantiate one and call its methods.
If it runs the same way in all contexts, then it doesn't need configurable behavior. If you don't need to be able to configure the behavior, then you don't need dependency injection (because all copies of this entity will use (copies of) the same dependencies.
When you do have a configurable behavior, then the analysis is going to need to look at scope. If you need to be able to change that behavior from one invocation to the next, then the caller is going to need to know about it. If the behavior changes less frequently than that, then you can start looking into whether "constructor injection" makes sense.
You know that you intend to use a single BannerReplacer for a given method invocation, so you can immediately start with a method that looks like:
class Banner {
void doTheThing(arg, bannerReplacer) {
/* do the bannerReplacer thing */
}
}
Note that this signature has no dependency at all on the lifetime of the bannerReplacer. More particularly, the BannerReplacer might have a longer lifetime than Banner, or a shorter one. We only care that the lifetime is longer than the doTheThing method.
class Banner {
void doTheThing(arg) {
this.doTheThing(arg, new BannerReplacer())
}
// ...
}
Here, the caller doesn't need to know about BannerReplacer at all; we'll use a new copy of the default implementation every time. Caller's that care which implementation is used can pass in their own.
class Banner {
bannerReplacer = new BannerReplacer()
void doTheThing(arg) {
this.doTheThing(arg, this.bannerReplacer)
}
// ...
}
Same idea as before; we're just using an instance of the BannerReplacer with a longer lifetime.
class Banner {
Banner() {
this(new BannerReplacer())
}
Banner(bannerReplacer) {
this.bannerReplacer = bannerReplacer;
}
void doTheThing(arg) {
this.doTheThing(arg, this.bannerReplacer)
}
// ...
}
Same idea as before, but now we are allowing the "injection" of a default implementation that can outlive the given instance of Banner.
In the long term, the comfort comes from doing the analysis to understand the requirements of the current problem, so that you can choose the appropriate tool.

How to set a breakpoint in Kotlin require with IntelliJ debugger?

The Kotlin standard library has a neat function require which is something like a runtime assert:
#kotlin.internal.InlineOnly
public inline fun require(value: Boolean, lazyMessage: () -> Any): Unit {
contract {
returns() implies value
}
if (!value) {
val message = lazyMessage()
throw IllegalArgumentException(message.toString())
}
}
When I am debugging, I would like to be able to set a breakpoint in this function, just before the exception is thrown. Like this, I would have the entire stacktrace and local variables visible in the debugger once a requirement is broken. However, this doesn't seem to work:
At first I thought that this is because require is an inline function. I made an experiment with one of my inline functions and the debugger halts as expected.
As a workaround I tried to set the debugger to break on exceptions, but the framework I am working with (Spring) throws a barrage of exceptions on each application start, making it extremely tedious to ignore the irrelevant exceptions.
I would like to know how to make it work, but I am also interested about the why of "it doesn't work".
It's currently not possible to set breakpoints in Kotlin for functions marked with a InlineOnly annotation, and require is one of such functions. Inline functions marked with this annotation don't provide additional debug information in order to save a line from the call site untouched in stack-traces, but it also ruins setting breakpoints inside (https://youtrack.jetbrains.com/issue/KT-24306).
You have spotted one workaround - using exception breakpoints (https://www.jetbrains.com/help/idea/creating-exception-breakpoints.html). IllegalArgumentException would be the best class in this case.
If there're calls in your code that don't work, they might be replaced to custom function as another workaround.
(The answer was updated. The previous version erroneously claimed that breakpoints in require might work for some calls.)

Is overloading a method without throwing an exception an antipattern?

We are currently designing an API for storing settings and we are considering having these two types of methods:
public Object getSetting(String key) {
// return null if key does not exist
}
public Object getSettingExc(String key) {
// throw a runtime exception if key does not exist
}
Somehow I feel that this just isn't right, but I can't think of any disadvantages except for doubling the number of functions in the API and perhaps decreased code readability (if I know the setting MUST exist, I think I should throw an exception explicitly rather than relying on the get method).
What are your opinions on this?
Exceptions are for exceptional occurrences, when the code cannot continue to function according to its advertised function.
Requesting a setting that isn't set is hardly exception-worthy. If "you" (i.e. the calling code) "know" that setting "must" exist, call getSetting(), check the return value for null, and then throw an exception yourself out of the knowledge that it should have been there. Add a meaningful message about what setting in which context wasn't found. (This is something only the caller knows.)
Don't delegate the throwing of the exception to code that doesn't know the context of the query or that the setting should be there, and needs to be told explicitly (by getting called under a different name). Also, getSettingExc() will most likely be only a null-check-and-throw wrapper around getSetting() anyway, so why not do it at a point where you can make the exception message so much more helpful?
IMHO. (And this is the point where I realize I should have voted-to-close instead of writing an answer...)
This is introducing a weird kind of coupling between the object structure and the potential error conditions. Regarding your comment:
I'm just trying to gather arguments to persuade other guys in my team.
The onus should be on the proponent of this design to justify it, not on you to justify against it. Nobody else uses this in any design I've ever seen.
This does however remind me of another design that maybe is what your team intended? Consider these two methods:
public Object getSetting(String key) {
// return the setting or throw an exception
}
public Object getSettingOrDefault(String key) {
// return the setting or a pre-determined default
}
This aligns the methods more with the functionality than with the error conditions. getSetting() can advertise that it might throw an exception, whereas getSettingOrDefault() can advertise that it will default to a specific value if none can be found in the settings.
If Java has optional parameters or something akin to that, getSettingOrDefault() might even accept as an argument a default to use in the event of no such setting. That might get a little kludgy for consuming code though, just sort of thinking out loud on that one.
Either way, the API should reflect the functionality and not the error conditions. Ideally there should be only one method, but if there's a noticeable need to differentiate between a method that throws and a method that doesn't (and I could certainly see that being the case in a language with checked exceptions), those two should align with the functionality rather than with the exception.
IMHO having two methods to do precisely the same operation indicates that you as the API designer did not complete the job of 'designing' your API. Choose one way or another, publicize it via the API (javadocs) and then the consumers will be consistent in their usage (one way or the other).

C#4 dynamic keyword - why not?

After reading many of the replies to this thread, I see that many of those who dislike it cite the potential for abuse of the new keyword. My question is, what sort of abuse? How could this be abused so badly as to make people vehemently dislike it? Is it just about purism? Or is there a real pitfall that I'm just not seeing?
I think that a lot of the revulsion that people are expressing to this feature boils down to "this is a bad language feature because it will allow bad developers to write bad code." If you think about it, by that logic all language features are bad.
When I run into a block of VB code that some genius has prefixed with On Error Resume Next, it's not VB that I curse. Maybe I should, I suppose. But in my experience a person who is determined to put a penny in the fuse box will find a way. Even if you empty his pockets, he'll fashion his own pennies.
Me, I'm looking forward to a more useful way of interoperating between C# and Python. I'm writing more and more code that does this. The dynamic keyword can't come soon enough for that particular use case, because the current way of doing it makes me feel like I'm a Soviet academic in the 1950s who's traveling to the West for a conference: there's an immense amount of rules and paperwork before I get to leave, I am pretty sure someone's going to be watching me the whole time I'm there, and most of what I pick up while I'm there will be taken away from me at the border when I return.
Some see it as a tool that will be abused. Like "Option Strict Off" and "On Error Resume Next" in VB which "pure" languages like C# and Java have never had.
Many said the same about the "var" keyword, yet I don't see it being abused, once it became understood that it wasn't the same as VB's "Variant"
It could be abused in places that lazy developers don't want type checking on classes and just try catch dynamic calls instead of writing "if blah is Blah ...".
I personally feel it could be used properly in situations like this recent question that I answered.
I think the ones really understanding it's power are those heavily into the dynamic .NET languages.
dynamic is bad because code like this will pop all over the place:
public dynamic Foo(dynamic other) {
dynamic clone = other.Clone();
clone.AssignData(this.Data);
return clone ;
}
instead of:
public T Foo<T>(T other) where T: ICloneable, IAssignData{
T clone = (T)other.Clone();
clone.AssignData(this.Data);
return clone;
}
The first one, has no static type info, no compile time checking, it's not self documenting, no type inference so people will be forced to use a dynamic reference at the call site to store the result, leading to more type loss, and all this spirals down.
I'm already starting to fear dynamic.
The real pitfall? Severe lack of documentation. The entire application's architecture exists in the mind of the person (or persons) who wrote it. At least with strong-typing, you can go see what the object does via its class definition. With dynamic-typing, you must infer the meaning from it's use, at best. At worst, you have NO IDEA what the object is. It's like programming everything in JavaScript. ACK!
When people realize that they don't get good IntelliSense with dynamic, they'll switch back from being dynamic-happy to dynamic-when-necessary-and-var-at-all-other-times.
The purposes of dynamic include: interoperability with dynamic languages and platforms such as COM/C++ and DLR/IronPython/IronRuby; as well as turning C# itself into IronSmalltalkWithBraces with everything implementing IDynamicObject.
Good times will be had by all. (Unless you need to maintain code someone else wrote.)
This is sort of like discussing public cameras, sure they can and will be misused but there are benefits to having them as well.
There is no reason why you couldn't outlaw the "dynamic" keyword in your own coding guideline if you don't need them. So whats the problem? I mean, if you want to do crazy things with the "dynamic" keyword and pretend C# is the some mutant cousin of JavaScript, be my guest. Just keep these experiments out of my codebase. ;)
I don't see a reason why the current way of invoking methods dynamicly is flawed:
It takes three lines to do it, or you can add a extension method on System.Object to do it for you:
class Program
{
static void Main(string[] args)
{
var foo = new Foo();
Console.WriteLine(foo.Invoke("Hello","Jonathan"));
}
}
static class DynamicDispatchHelper
{
static public object Invoke(this object ot, string methodName, params object[] args)
{
var t = ot.GetType();
var m = t.GetMethod(methodName);
return m.Invoke(ot, args);
}
}
class Foo
{
public string Hello(string name)
{
return ("Hello World, " + name);
}
}