What is the difference between Groovy Micronaut's #Client injected RxHttpClient vs RxHttpClient.create? - groovy

I'm creating a Micronaut HTTP Client using the #Client annotation in Groovy, and the compiler complains if I use anything other than a static constant. However, this limits me from being able to change the URL per environment by passing in a config value.
So I tried using RxHttpClient.create(myUrl) in my service instead, and the same request I'm making returns a 403. The RxHttpClient docs say
Create a new HttpClient. Note that this method should only be used
outside of the context of an application. Within Micronaut use Inject to > inject a client instead.
This doesn't explain why I shouldn't use the create method, and I'm left with an inability to make requests to different servers on different environments. What is the difference between the two clients I'm creating?

The #Client annotation will inject a managed client that has been dependency injected with additional instrumentation features for tracing, propagation etc. By using create Micronaut cannot dependency inject the instance so certain features of the framework won't work.
In addition with create you have to ensure you manually close the client since Micronaut cannot manage the life cycle and cleanly shutdown the client when the application shuts down.
Finally regarding using a static constant to #Client, it is not true that this limits you since the value can include placeholders. For example:
#Client("${my.server}")
Then in application.yml you can configure:
my:
server: http://foo.com
Or even better you can use the new HTTP services feature. See https://docs.micronaut.io/latest/guide/index.html#serviceDiscoveryManual

Related

Unrecognized Spring cache annotations when self-invoking a method from within the same bean

Dear Spring Cache project community,
currently I'm implementing an Apache CXF-based Spring (version 4.1.5) web service endpoint using the contract 1st approach. Here, I observe when annotating a public method within my web service class, the Spring cache annotations "#Cachable" are ignored each time I call this method in a self-invoked way within the same bean. This could be proven when taking a look on the cache repository (via JMX) of the underlying cache provider (here: EhCache). There, no filling of the cache takes place.
After taking a look on the current Spring documentation below
Enable caching annotations and
The dispatcher servlet I assume it might be due to the fact that:
<cache:annotation-driven/> only looks for #Cacheable/#CachePut/#CacheEvict/#Caching on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for beans in your controllers, and not your services. See Section 17.2, “The DispatcherServlet” for more information.
Currently, an Apache CXF "CXFServlet" registered within the "web.xml" deployment descriptor is starting a Spring WebApplicationContext using the "cxf-servlet.xml" Spring application context file by default. There, the <cache:annotation-driven/> is located.
Or is it maybe due to the fact that I'm calling the #Cacheable annotated method from within the same Spring bean so that the generated Spring proxy is bypassed? Details can be found in the "Proxy mechanisms" chapter (9.6) of the Spring documentation as well.
But I do not know how to change the behaviour so that my method results are being cached. Do you have any ideas? Or are my assumptions I posted above incorrect?
Dear Spring community,
I found the important comment within the Spring documentation that approves my assumption:
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with #Cacheable - considering using the aspectj mode in this case. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct.
In consequence this means refactoring the code when relying on Spring AOP and its proxy mode technique or switching the mode from "proxy" to "aspectj" <cache:annotation-driven mode="aspectj"/>. This allows using self-invoking methods within the same class as AOP does static respectively dynamic weaving and so manipulates the byte code directly.

Combining pyramid with cornice and basic auth does password checking twice, how to prevent?

Currently I am working on a project that combines basic authentication with the cornice / pyramid framework.
From the logging I observe that every time a url is access the used credentials get checked twice. Since in our user case this does involve a lot of database checks, it is a potential target for an (unintended) DoS attack.
In my view I define a cornice Service with a factory.
In my app setup I configured the pyramid provided BasicAuthenticationPolicy with the resource intensive check as a callback for authentication
Also in the app setup I configure the pyramid provided ACLAuthorizationPolicy for authorisation.
So I was wondering, what I am missing, as I would really like to prevent the second check to take place. (Should I cache this on the request object in some secure way?)
Found by studing the code this is intended behaviour.
This behaviour is only triggered when the authenticated_userid property is used (which I do).
Solved this issue by 'caching' call's to my authentication function via a decorator. Which should be fine as the same objects will be referenced via the function parameters.
Documentation can be found in the pyramid package pyramid/authentication.py

Can one instance of a ServiceClient be used in multiple threaded application (MVC)

In my ASP.NET MVC controllers, I want to call a servicestack based service (not hosted in MVC site). In order to make the code testable, I want to inject this service client into the contoller constructor.
Assuming I have my own class that inherits from JsonServiceClient, can I use a singleton of that service client for all the MVC calls? This means the client would have to be thread safe.
Either the (Autofac) registration can be a singleton:
builder.RegisterType<SomeServiceClient>().SingleInstance();
or it has to be per http request:
builder.RegisterType<SomeServiceClient>().InstancePerHttpRequest();
Found a blog article where another servicestack user seems to use a singleton, but I was not sure: Blog Article Showing an Example
Each request is generally re-entrant so it's mostly ThreadSafe to use as a Singleton, the one caveat is that it shares the same CookieContainer, whilst the ServiceClients doesn't mutate the CookieContainer Collection itself, the underlying WebRequest would and it's not known whether WebRequest synchronizes access around it - although I've never personally seen any issues with them.
You can disable Cookies being used (i.e. if your client doesn't require a session) with:
client.StoreCookies = false;

Why does ServiceStack's AppHostBase.Configure take a Container parameter?

AppHostBase already contains a Container property (which resolves to EndpointHost.Config.ServiceManager.Container if defined), so why not just use Instance.Container (e.g., for registering dependencies, plugins, etc.) inside Configure or elsewhere inside any AppHost implementations?
I do note that Configure is a public call, so it could technically be called from anywhere, although it appears that AppHostBase.Init() is the only place in the ServiceStack codebase that does so.
All configuration and registration should happen within the context of the AppHost.Configure(Container) method, after which point it should remain immutable (readonly) for ThreadSafety.
The Container is passed in because that's where all the application dependencies should be registered on. The Container property itself should therefore be treated as read only which is why core classes like IAppHost only exposes a IResolver.TryResolve method.

ServiceStack service for none standard rest + overall confusion

I would really like to utilize servicestack for a service I need to write but I'm hitting a mental block wrapping my mind around how it works, and more precisely how I can make it work for my intents and purposes. I don't have a strong asp background, mainly backend, so maybe that's why the mental block.
I have a legacy platform to which I connect via native c++ api. I have warped the native api in cli as a .net class library, this would be my equivalent of the Todo repo being injected in the samples.
The data moving back and forth is exposed in the class lib as value structs. For example account would be defined like this:
struct Account{
int id;
string name;
string password;
...
}
Order would be something like this:
struct Order{
int orderId;
int account;
string comment;
...
}
The lib exposes a lot of functionality and operations for all sorts of different objects defined similarly to the above. What i'm trying to understand is this:
1) How do I register the api with the container? More precisely, I don't understand how the Register method knows what type its supposed to get. In the todo sample everything is defined in the same assembly so its hard to see how the backend gets injected.
2) Is there a way to manage the lifecylce of the back end in the framework. Can I make it a singleton across all connections.
3) Do I have to wrap my structs in classes that map fields to a request. Not quiet clear on how the request objects are defined, it seems that the content of the request should be fields that would translate to urls of fieldname/type for operations. If there is a way to not have to wrap, how do I then limit which fields to expose in the api and which not to.
4)Do I absolutely have to create a service per data type, so in the structures above would I have to implement one service for Orders and one for Accounts of is there a way to combine them into one. I love that ss can be converted to talk over mq's, would making a combined service make it difficult to operate over mq's in the future, what are the cons to this approach.
5) Lastly, I would like to expose operations in the api that, afaik would violate the rest contract. Something like: archive accounts older then.... This would be an operation that returns success/fail status no update/delete ect. Essentially, drive some functionality via an http request. Is this possible in ss, if so, does using it in this way have any debilitating consequences to the framework's operation...
1) To register your API you will want to use the built in IoC with Funq.
container.Register(c => new LegacyApiService())
.ReusedWithin(ReuseScope.Container);
Funq is able to automatically wire these Services in your API Services. Take a look at https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container.
You can also resolve anywhere container is available using the TryResolve method.
2) You can controls the Object lifetime with Funq by specifing ReuseScopes when you register them. You will want to look at
ReuseScope.Container: Singleton scope
// a instance is used per application lifetime
3) You are going to need to create plan old classes (DTOs) for your structs. This is necessary for ServiceStack. All your DTOs public properties will get serialized. You can also optionally use DataMemberAttribute and the IgnoreDataMemberAttribute to control what public properties get serialized.
4) You will need to have a sservice per request DTO. However, you can keep this code at a minimun and call a centralized business layer. This is necessary since each route + verb needs to have a distinct operation, hence the one service class per DTO.
5) You can easily define more routes and there is nothing that forces you to adhere to REST rules, you are free to implement the HTTP verbs as you see fit. You can easily create specialized routes on GETs that perform an action such as archiving. There are no debilitating consequences here, just perhaps confusion to your API consumers. Just be sure everyone is clear how the API works with documentation.

Resources