Micronaut GRPC execute database call on same thread as grpc request

83 Views Asked by At

I have a Micronaut application using micronaut-grpc and perform calls to a Postgres database that has an RLS policy enabled which uses a session attribute to perform the check. In order to set this attribute every time the Connection::getConnection method is called it performs a call to the database to set the attribute

public class TenantDataSource extends HikariUrlDataSource {

    public TenantDataSource(HikariConfig configuration) {
        super(configuration);
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection connection = super.getConnection();
        try (PreparedStatement preparedStatement = connection.prepareStatement("select set_config('tenant', ?, false)")) {
            preparedStatement.setString(1, ThreadLocalTenant.get());
            preparedStatement.execute();
        }
        return connection;
    }
}

public class ThreadLocalTenant {

    private static final ThreadLocal<String> TENANT = new ThreadLocal<>();

    public static void set(String tenant) {

        TENANT.set(tenant);
    }

    public static String get() {

        return TENANT.get();
    }

}

The problem I'm facing here is that while the user request is being executed on, let's say, thread-1 of the IO pool the code above that sets the attribute sometimes it's executed on a different thread making it impossible to access to the tenant id from the ThreadLocalTenant class.

Previously we used the grpc Context but we also have to support regular HTTP endpoints so we need something generic.

Is there any way to make the whole request execute on the same thread?

I've tried different configurations of the micronaut executors but nothing worked so far

0

There are 0 best solutions below