how to consume custom spring-boot-actuator metrics - spring-boot-actuator

I've got a use case where I need to keep track of processing time metrics for a given component and use that as a feedback loop for tuning purposes within my spring-boot application. I thought I'd use a custom metric via an autowired GaugeService in the component I need to monitor, which is working fine and I can see my metrics in the /metrics endpoint. What I'm having trouble with is how to consume those metrics in application code. I would ideally like to receive every gauge submit result and compute a weighted moving average. Is this not a good use case for spring-boot-actuator metrics?

Reading the metrics information via code should be quiet possible via Injecting MetricsEndpoint bean into your application code as usual we inject anyother bean.
MetricsEndpoint bean is defined by EndpointAutoConfiguration.
Every Endpoint defines [#ReadOperation, #WriteOperation, #DeleteOperation] annotated method in order for that end point to be adapted by exposing technology like JMX, Spring webflux etc.
In your case you may be only interested in calling the #ReadOperation of MetricsEndpoint which means two method : listNames or metric. See the given link for more information.
Now when/how often you call this endpoint depends on you only.
Hope this helps.

Related

Managing a connection to an external component in an Aggregate

I just discovered Axon framework and am very eager to use it as it answers a lot of my questions and concerns about DDD.
The first project I'd like to use it on contains small cameras which are controlled via the GigEVision protocol (over TCP and UDP for the control and stream channels). I think my problem would be the same for any case where we maintain a connection to an external component or more generally we want to link an external component lifecycle to Axon's lifecycles.
I'd like to have an Aggregate named Camera to which I can send Commands to grab 1 image or start grabbing N images at a certain FPS.
What I'm not sure about is how to manage the connection to an external component in my Aggregate.
- Should I inject the client to my camera in my Camera Aggregate and consider connecting to it as part of my protocol / business commands? In this case how would I link the camera lifecycle (a camera get disconnected all of a sudden) to the aggregate lifecyle (create a corresponding CameraDisconnectedEvent)?
- Should the connection be handled in a side car Saga which get the camera client injected, the saga starting on ConnectionRequestedEvent and stopping as soon as we get a connection error from the camera. I would get the same issue of linking the connection lifecycle to the lifecycle of the Saga I think.
- Am I leaking implementation details in the business layer and should manage the issue an other way?
- Am I just using the wrong tool for this job and should not try to force it into Axon?
Thank you very much in advance, hope my message and issues make sense.
Best regards,
First and foremost what you should do, is ensure the language spoken by the GigEVision protocol by no means transitions over into your other domain.
These two should be separate and remain so, as they cover different concerns.
This brings to light the necessity to have a translation layer of some sort.
More formuly called a context mapping. From a DDD perspective, you would take this even further by talking about an Anti-Corruption Layer.
The name already says it, you add a layer to ensure you are not corrupting your domain logic with that from another domain.
Another useful topic to read up on here would be the notion of a Bounded Context.
I digress though, let's go back to the problem at hand: where to position this anti-corruption layer.
What is currently unclear to me, is what domain requirements are in place why the connection is required to be maintained all the time when requesting for images.
Is the command you want to send requesting for a live feed? Or just "some" images from a given time frame?
In both scenarios I am not immediately convinced that any of these operations requires the validation through a single Camera aggregate to be honest.
You could still model this in a command and event format, as the messaging paradigm is very helpful to allow clean segregation of concerns.
But given the current description, I am uncertain whether you need DDD's idea of an Aggregate to model a single Aggregate in.
I might be wrong on this note, but I just don't know enough about your domain at this stage.
That's my two cents to the situation, hoping this helps!

Validating empty Guids in Api layer

Let's say I have an API endpoint GET api/customers. My API request model contains a Guid.
In the business layer I throw an error if that Guid is empty.
Should I catch this error in the API layer or let it propagate to lower layers?
Should I check that Guid against empty in the API layer?
using annotations
classic if check, before calling the business logic
Is there any standard way to handle empty Guids in API design?
It is better to define as Nullable<Guid> in your request API model.
So that it will have null value instead of empty.
And you can add also checking logic into your API Controller before calling business logic.
Generally speaking a Controller's Action should be responsible for the followings:
Receive and try parse data (header, route, form)
Perform preliminary checks
Call service / business layer
Translate the response from the below layer to a http response
In my opinion checking against Guid.Empty is the same as checking against whitespaces or null. If the provided data does not met the requirements then the best thing what you can do is to fail fast or use fallback.
I have participated in several discussions about where this kind of validation should belong. As always it depends. But my personal rule of thumb (I have followed this through many projects) looks like this:
Presentation layer should check against syntactic issues (check against default values as well)
Business layer should check against semantic issues (cross property / cross entity checks as well)
Persistence layer should check against dataset consistency
My point is that at the end of the day you want to have the followings:
Responsibilities of different layers are understood by everyone
Each validation logic can be easily determined where it should belong
Validation failures can be easily tracked back

Reason to integrate Spring Web-flow with Spring MVC

Why(In what scenarios) do we need to integrate Spring Webflow with Spring MVC? Both these frameworks are used to create web-app and I do not see any point why we would integrate them. I would appreciate if someone could clarify me about it.
This is really late but I don't see a satisfactory answer to this question and would like to share an approach I had tried in a recent project which I feel is better than the spring web flow approach which is strictly tied down to spring views and unnecessarily adds to the already existing xml load . I created a SPA(Single Page Application) using angular js with Spring MVC. In angular js I did not use routers or state, rather I created a div within the controller like below
On the server side to capture all possible transitions from one frame(I am referring to a particular screen in the SPA) to another I created a tree of rules using MVEL . So in the database I had a structure which stored a tree of rules for every frame . The data in the MVEL expressions were being set by the various services each action invoked. Thus on any action the following steps were followed.
1) Validate the action.
2) Invoke various services.
3) Capture the data from these services and merge it with the existing data of the user.
4) Feed this captured data into collection of rules for each frame along with the details of the current frame.
5) Run the rules of the tree w.r.t to current frame and fetch its output.
6) If there is only one transition then that is the final transition. If there are 2 transitions and one is default then ignore the default transition and use the other transition.
7) Return the template name of the transition to the angular controller and set the value of the page variable in the scope of the controller.
Using this approach all my services had to do was store data in different data fields w.r.t a particular action. All the complex if-else conditions for Web Flows or any complex process definitions(like the one defined in Spring-Web Flow) were not required. The MVEL rule engine managed all that and since it was all in the database it could be changed without needing a server re-start.
I believe this generic approach with MVEL is a flexible approach which comprehensively handles the problem of a convoluted flow without making the application code a mess or adding additional unnecessary xml files.
We combine both. Web Flow for the multi-step activities, where it doesn't make sense to jump into the middle of a process, and plain-MVC Controllers for the single-step activities. Things you might bookmark individually.
For example, an appointment-scheduling application, "find my appointment" might be a single Controller that accepts identifying information. "Make a new appointment" is a flow, with multiple steps of selecting a location, date, time, confirm the appointment, etc.
If your application have complex Flow pages, events which need to be defined as Finite state machine then use Webflow. It would be justified to use webflow for website where you buy Insurance, Flight Tickets. Web Flow conditions are like:
There is a clear start and an end point.
The user must go through a set of screens in a specific order.
The changes are not finalized until the last step.
Once complete it shouldn't be possible to repeat a transaction accidentally

Filter api model properties by user permission level in ASP.NET Core

We want to filter / hide / clear specific api model properties based on the user permission level.
The model itself will not differ. Just no return for those.
I found a lot of different ideas online:
switch(userrole) and call different logic methods
pass user role to logic
reflection to clear properties in the response (I hate this idea)
middleware to redirect the user to different actions
What is the recommended way to filter api model properties for specific roles?
It's hard to give any real specifics with what you've provided, but generally, I'd say this should go into your mapping logic. Utilize view models/DTOs to accept data from client requests. Then map that data from the view model/DTO to your entity instance. During this process, you can make decisions based on the user's role/permission set about what properties should or should not be mapped over. All of this logic can be factored out into a separate class or library of classes. Ultimately it doesn't really matter what the client sends. You can't control that anyway. You just need to ensure that they ultimately can't set any properties they don't have "access" to, and mapping logic is a great place for that.

Best approach to wait untill all service calls returned values in Flex PureMVC

I am writing an Adobe AIR application using PureMVC.
Imagine that I have an page-based application view ( using ViewStack ), and user is navigating through this pages in some way ( like clicking the button or whatever ).
Now for example I have an Account Infromation page which when instantiated or showed again needs to load the data from WebService ( for example email, account balance and username ), and when the data is returned I want to show it on my Account Information page in the proper labels.
The problem is when I will execute this three Web Calls, each of them will return different resultEvent at different time. I am wondering what is the best way to get the information that ALL of the service calls returned results, so I know that I can finally show all the results at once ( and maybe before this happens play some loading screen ).
I really don't know much about PureMVC, but the as3commons-async library is great for managing async calls and should work just fine in any framework-setup
http://as3commons.org/as3-commons-async/
In your case, you could create 3 classes implementing IOperation or IAsyncCommand (depending on if you plan to execute the operations immediately or deferred) encapsulating your RPCs.
After that is done you simply create a new CompositeCommand and add the operations to its queue.
When all is done, CompositeCommand will fire an OperationEvent.COMPLETE
BTW, the library even includes some pre-implemented common Flex Operations, such as HTTPRequest, when you download the as3commons-asyc-flex package as well.
I would do it in this way:
Create a proxy for each of three information entities (EMailProxy, BalanceProxy, UsernameProxy);
Create a delegate class which handles the interaction with your WebService (something like "public class WSConnector implements IResponder{...}"), which is used by the proxies to call the end ws-methods;
Create a proxy which coordinates all the three results (CoordProxy);
Choose a mediator which will coordinate all the three calls (for example it could be done by your ApplicationMediator);
Create notification constants for all proxy results (GET_EMAIL_RESULT, GET_BALANCE_RESULT, GET_USERNAME_RESULT, COORD_RESULT);
Let the ApplicationMediator get all 4 notifications;
it is important that you should not only wait for all three results but also be ready for some errors and their interpretation. That is why a simple counter could be too weak.
The overall workflow could look like this:
The user initiates the process;
Some mediator gets an event from your GUI-component and sends a notification like DO_TRIPLECALL;
The ApplicationMediator catches this notification, drops the state of the CoordProxy and calls all 3 methods from your proxies (getEMail, getBalance, getUsername).
The responses are coming asynchronously. Each proxy gets its response from the delegate, changes its own data object and sends an appropriate notification.
The ApplicationMediator catches those notifications and changes the state of the CoordProxy. When all three responses are there (may be not all are successful) the CoordProxy sends a notification with the overall result.
I know it is not the best approach to do such an interaction through mediators. The initial idea was to use commands for all "business logic" decisions. But it can be too boring to create the bureaucracy.
I hope it can help you. I would be glad to know your solution and discuss it here.

Resources