Spring reactive WebSession with JDBC (or R2DBC) - spring-security

I'm trying to migrate my Servlet-based application to Webflux and got stuck with session management. I've been using Spring session with Jdbc implementation (backed by PostgreSQL) for a while and my config looks like this:
#Configuration
#EnableSpringHttpSession
public static class SessionConfig {
#Bean
public MapSessionRepository sessionRepository() {
return new MapSessionRepository(new ConcurrentHashMap<>());
}
}
Now, as I understood documentation correctly, servlet-based HttpSession has been replaced with WebSession and I need to provide configuration like the following:
#Configuration
#EnableSpringWebSession
public class SessionConfig {
#Bean
public ReactiveSessionRepository sessionRepository() {
return ???
}
}
But I could not find any support for relational databases as there are only 2 implementations of org.springframework.session.ReactiveSessionRepository (from "org.springframework.session:spring-session-core:2.2.2.RELEASE"):
Basic one - ReactiveMapSessionRepository
Redis-based one - ReactiveRedisSessionRepository
but unfortunately, they do not satisfy my requirement.
I also could not find any notes neither for "org.springframework.session:spring-session-jdbc" support for WebSessions, nor for new R2DBC.
Is it possible to back WebSessions by relational database (e.g. Postgres) and if it is, how can I achieve this (which implementation should I use)? I know there are some issues with non-blocking operations support for relational databases but I wonder if I missed something and it's still possible.
Thanks in advance

You are correct that Spring Session does not provide a JDBC implementation of ReactiveSessionRepository, since JDBC is of a blocking nature.
When building a reactive web application, currently only Redis and MongoDB can be auto-configured.
If it's necessary for you to use JDBC with WebFlux, it is possible to back WebSession by relational database, by configuring a custom implementation of ReactiveSessionRepository.
First, make sure you consider whether WebFlux is a good fit for your use case.
From the Spring Framework documentation:
If you have blocking persistence APIs (JPA, JDBC), or networking APIs to use, then Spring MVC is the best choice for common architectures at least. It is technically feasible with both Reactor and RxJava to perform blocking calls on a separate thread but you wouldn’t be making the most of a non-blocking web stack.
If you do implement a custom ReactiveSessionRepository, you may find this section of the Spring Session docs useful.

Related

How do you deal with shared data in stateless grails service

I was trying to implement a grails SearchService that indexes certain text and stores it in memory for faster lookup. In order to store this data, I was trying to use a private static property in the Service to store the data, but the property was randomly resetting values. After rereading documentation, I realized that this is likely because grails services are supposed to be stateless since the employee the singleton pattern. Still, not sure I understand how a static variable can vary. Does the JVM load separate copies of service classes per thread? Not sure I'm wrapping my head around what's happening.
Nonetheless, now that I know I can't rely on static variables to store application-wide data, what's the best approach to store and access data for use across the application, while keeping synchronization and avoiding races?
Caused by: java.lang.IllegalStateException: Method on class [TEXTSTORE] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
at SearchService.buildIndex(SearchService.groovy:63)
at SearchService$_indexAllDomains_closure2.doCall(SearchService.groovy:42)
at SearchService.indexAllDomains(SearchService.groovy:41)
at SearchService.$tt__rebuildIndex(SearchService.groovy:48)
at SearchService.afterPropertiesSet(SearchService.groovy:35)
... 4 more
You seem to be a bit confused about services in Grails. There is no reason why a service (defaulting to singleton) can't have shared state. It's not uncommon for a service to populate some cached or indexed data when it is created so it can be used by multiple callers.
Most often this is done by implementing the org.springframework.beans.factory.InitializingBean interface and making use of the afterPropertiesSet() method which is called when the service (Spring bean) has been created in the application context and all dependencies have been resolved.
For example:
package com.example
import org.springframework.beans.factory.InitializingBean
class MyExampleService implements InitializingBean {
private List data
def otherService
void afterPropertiesSet() {
data = otherService.doSomethingToFetchData()
}
// .. other stuff
}
By hooking into the lifecycle of the bean you can be fairly sure that even in development (when your service reloads because you've changed some code) it will still have the data needed.

how to invoke unsecured proxy while using spring security annotations?

I am using spring security annotations in my project. There are scenarios when i want to invoke security-less version of the annotated object. Spring by default creates a security-enabled proxy of the annotated object and uses it for autowiring in the code, is there any way that i can achieve this using spring ?
An obvious way to do this would be to manually create proxy classes corresponding to each class for which i want this feature have those methods annotated and the implementation of these methods just delegate it to the actual object.
As an option in a case of JDK proxies you can get actual bean at runtime:
MyBean proxy;
if(AopUtils.isJdkDynamicProxy(proxy)) {
MyBean actualInstance = (MyBean) ((Advised)proxy).getTargetSource().getTarget()
}
actualInstance.doSomethingSecured(); // no advice related to this method will be called
// so your security annotation will be ignored (transactions, cache, and everething that requires AOP too...)
But from architectural point of view approach with manual proxies looks less error phrone (except if you absolutely sure that you do not need security and all another possible aspects too).
You can improve readability using generics:
MyBean actualInstance = extractProxyTarget(proxy, proxy.getClass());
actualInstance.doSomethingSecured();

Grails: examples of good use of .memoize()?

What would be the syntax for memoizing a service method that is side-effect free and only does lookups? Would the memo persist from session to session or would it be kindof purposeless in the web world? Are there some examples of good places to use .memoize() in a grails app?
class DetermineStuffService{
def figureThisOut(def whatever){
//look up all sorts of stuff and do some heavy side-effect free processing
return nastyHashmap
}
}
So in a controller can I somehow call DetermineStuffService.figureThisOut(someRandomObject) and take advantage of .memoize()?
One problem with this is that memoize() only works on closures. Closures are objects, so if you store one in your service, it is "state".
A better way of caching services in grails is with the Spring Cache plugin. Then to cache the result of a service method, just annotate the method with #Cacheable. It has support for multiple caches, automatically flushing, and caching controller output as well.

Do we need to use the Repository pattern when working in ASP.NET MVC with ORM solutions?

I am bit curious as to what experience other developers have of applying the Repository pattern when programming in ASP.NET MVC with Entity Framework or NHibernate. It seems to me that this pattern is already implemented in the ORM themselves. DbContext and DbSet<T> in the Entity Framework and by the ISession in NHibernate. Most of the concerns mentioned in the Repository pattern - as catalogued in POEE and DDD - are pretty adequately implemented by these ORMs. Namely these concerns are,
Persistence
OO View of the data
Data Access Logic Abstraction
Query Access Logic
In addition, most of the implemententations of the repository pattern that I have seen follow this implementation pattern - assuming that we are developing a blog application.
NHibernate implementation:
public class PostRepository : IPostRepository
{
private ISession _session;
public PostRepository(ISession session)
{
_session = session;
}
public void Add(Post post)
{
_session.Save(post);
}
// other crud methods.
}
Entity Framework:
public class PostRepository : IPostRepository
{
private DbContext _session;
public PostRepository(DbContext session)
{
_session = session;
}
public void Add(Post post)
{
_session.Posts.Add(post);
-session.SaveChanges();
}
// other crud methods.
}
It seems to me that when we are using ORMs - such as Nhibernate or Entity Framework - creating these repository implementation are redundant. Furthermore since these pattern implementations does no more than what is already there in the ORMS, these act more as noise than helpful OO abstractions. It seems using the repository pattern in the situation mentioned above is nothing more than developer self aggrandizement and more pomp and ceremony without any realizable techical benefits. What are your thoughts ??
The answer is no if you do not need to be able to switch ORM or be able to test any class that has a dependency to your ORM/database.
If you want to be able to switch ORM or be able to easily test your classes which uses the database layer: Yes you need a repository (with an interface specification).
You can also switch to a memory repository (which I do in my unit tests), a XML file or whatever if you use repository pattern.
Update
The problem with most repository pattern implementations which you can find by Googling is that they don't work very well in production. They lack options to limit the result (paging) and ordering the result which is kind of amazing.
Repository pattern comes to it's glory when it's combined with a UnitOfWork implementation and has support for the Specification pattern.
If you find one having all of that, let me know :) (I do have my own, exception for a well working specification part)
Update 2
Repository is so much more than just accessing the database in a abstracted way such as can be done by ORM's. A normal Repository implementation should handle all aggregate entities (for instance Order and OrderLine). Bu handling them in the same repository class you can always make sure that those are built correctly.
But hey you say: That's done automatically for me by the ORM. Well, yes and no. If you create a website, you most likely want to edit only one order line. Do you fetch the complete order, loop through it to find the order, and then add it to the view?
By doing so you introduce logic to your controller that do not belong there. How do you do it when a webservice want's the same thing? Duplicate your code?
By using a ORM it's quite easy to fetch any entity from anywhere myOrm.Fetch<User>(user => user.Id == 1) modify it and then save it. This can be quite handy, but also add code smells since you duplicate code and have no control over how the objects are created, if they got a valid state or correct associations.
The next thing that comes to mind is that you might want to be able to subscribe on events like Created, Updated and Deleted in a centralized way. That's easy if you have a repository.
For me an ORM provides a way to map classes to tables and nothing more. I still like to wrap them in repositories to have control over them and get a single point of modification.
I think it make sense only if you want to decrease level of dependency. In the abstract you can have IPostRepository in your infrastructure package and several independent implementations of this interface built on top of EF or NH, or something else. It useful for TDD.
In practice NH session (and EF context) implements something like the "Unit of Work" pattern. Furthermore with NH and the Repository pattern you can get a lot of bugs and architectural issues.
For example, NH entity can be saved bypassing your Repository implementation. You can get it from session (Repository.Load), change one of its properties, and call session.Flush (at the end of request for example, because Repository pattern doesn't suppose flushing) - and your changes will be successfully processed in db.
You've only mentioned basic CRUD actions. Doing these directly does mean you have to be aware of transactions, flushing and other things that a repository can wrap up, but I guess the value of repositories becomes more apparent when you think about complex retrieval queries.
Imagine then that you do decide to use the NHibernate session directly in your application layer.
You will need to do the equivalent of WHERE clauses and ORDER BYs etc, using either HQL or NHibernate criteria. This means your code has to reference NHibernate, and contains ideas specific to NHibernate. This makes your application hard to test and harder for others unfamiliar with NH to follow. A call to repository.GetCompletedOrders is much more descriptive and reusable than one that includes something like "where IsComplete = true and IsDeleted = false..." etc.
You could use Linq to NHibernate instead, but now you have the situation where you can easily forget that you're working on an IQueryable. You could end up chaining Linq expressions which generate enormous queries when they execute, without realising it (I speak from experience)! Mike Hadlow sparked a conversation on essentially this topic in his post Should my repository expose IQueryable.
N.b. If you don't like having lots of methods on custom repositories for different queries (like GetCompletedOrders), you can use specification parameters (like Get(specification)), which allow you to specify filters, orderings etc. without using data access language.
Going back to the list of benefits of repository that you gave:
Persistence
OO View of the data
Data Access Logic Abstraction
Query Access Logic
You can see that points 3 and 4 are not provided for by using the persistence framework classes directly, especially in real world retrieval scenarios.

Resources and Examples of using MEF for DI/IoC

I've searched high and look for samples about using MEF for DI. I know its not DI but from what I hear (really hear in podcasts) it can be used as such...but I can't find any blog posts or samples.
I am using MEF in this project already (to support plugins) and thought it would be nice to leverage for DI also.
Maybe I am barking up the wrong tree?
This can be described by an example. For instance, let's say you have a core library that you base all your bespoke applications on. Call it MyCompany.Core. Normally, every application you write has to contain a reference to MyCompany.Core, and then the application has to take care of bootstrapping and calling into MyCompany.Core to start the appropriate services, etc., in the correct order. This doesn't make much sense when you consider that the core itself probably knows better how it's supposed to be started up, etc.
To use MEF for dependency injection, your core would do this:
[Import("/Application", typeof(IBespokeApplication))]
private IBespokeApplication bespokeApplication;
The core itself would contain the application startup code, and might call something like this once it had started up all of its services:
bespokeApplication.Start();
In the bespoke application, you have to export yourself:
[Export("/Application", typeof(IBespokeApplication))]
public class MyApplication : IBespokeApplication
{
public void Start()
{
/* start app */
}
}
Now the bespoke application could contain a direct reference to MyCompany.Core, and could call services directly, or you could even expose the services as Exports and Import them into the application. For instance, in the core:
[Export("/LoggingService", typeof(ILoggingService))]
public class NLogLoggingService : ILoggingService
{
/* ... */
}
Then in the bespoke application:
[Import("/LoggingService", typeof(ILoggingService))]
private ILoggingService loggingService;
...and when you want to use it:
loggingService.LogInformation("My Message");
As far as I can tell from the literature, that's the essence of dependency injection.

Resources