Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(api): implement Hibernate second-level caching for core entities using Caffeine JCache (#7504)

brioseaaa24beb64f
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index 660167ada0..e3d13bd91a 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -84,6 +84,7 @@ public class ApplicationProperties {
private Mcp mcp = new Mcp();
private InternalApi internalApi = new InternalApi();
private Cluster cluster = new Cluster();
+ private SecondLevelCache secondLevelCache = new SecondLevelCache();
private Policies policies = new Policies();
@PostConstruct
@@ -603,6 +604,22 @@ public class ApplicationProperties {
}
}
+ /**
+ * Hibernate second-level cache scope, bound under the top-level {@code secondLevelCache.*}
+ * prefix.
+ */
+ @Data
+ public static class SecondLevelCache {
+
+ /**
+ * The JCache regions are process-local: a write on one instance cannot evict another
+ * instance's entries, so a revocation or role change reaches the other instances only when
+ * the region TTL lapses. Multi-instance deployments either set {@code cluster.enabled=true}
+ * (which disables the cache) or turn it off here.
+ */
+ private boolean enabled = true;
+ }
+
/** Cluster backplane config, bound under the top-level {@code cluster.*} prefix. */
@Data
public static class Cluster {
diff --git a/app/proprietary/build.gradle b/app/proprietary/build.gradle
index ce93af4d5b..7130c4cf49 100644
--- a/app/proprietary/build.gradle
+++ b/app/proprietary/build.gradle
@@ -30,7 +30,9 @@ dependencies {
api 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
api 'org.springframework.boot:spring-boot-starter-mail'
api 'org.springframework.boot:spring-boot-starter-cache'
+ api 'org.hibernate.orm:hibernate-jcache'
api 'com.github.ben-manes.caffeine:caffeine'
+ api 'com.github.ben-manes.caffeine:jcache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
// Supplies GenericObjectPoolConfig for the Lettuce pool, which today backs only the single
// shared native connection; headroom for a future dedicated-connection path.
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/Team.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/Team.java
index 661e42c771..5ed11faddb 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/Team.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/Team.java
@@ -5,6 +5,8 @@ import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.proxy.HibernateProxy;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -21,6 +23,8 @@ import stirling.software.proprietary.security.model.User;
@Entity
@Table(name = "teams")
@EntityListeners(TeamEntityListener.class)
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "teams")
@NoArgsConstructor
@Getter
@Setter
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java
index 41dac6cc7f..5e1110b03b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/UserLicenseSettings.java
@@ -3,6 +3,9 @@ package stirling.software.proprietary.model;
import java.io.Serial;
import java.io.Serializable;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
import jakarta.persistence.*;
import lombok.*;
@@ -13,6 +16,8 @@ import lombok.*;
*/
@Entity
@Table(name = "user_license_settings")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "user-license-settings")
@NoArgsConstructor
@AllArgsConstructor
@Getter
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceEntity.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceEntity.java
index 728612742e..d843ce1184 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceEntity.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/source/SourceEntity.java
@@ -2,6 +2,10 @@ package stirling.software.proprietary.policy.source;
import java.io.Serializable;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
@@ -22,6 +26,8 @@ import stirling.software.proprietary.integration.crypto.LegacyDecryptStringConve
*/
@Entity
@Table(name = "policy_sources")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "policy-sources")
@NoArgsConstructor
@Getter
@Setter
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/PolicyEntity.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/PolicyEntity.java
index fa639b5c19..d1ff4f98e5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/PolicyEntity.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/store/PolicyEntity.java
@@ -2,6 +2,10 @@ package stirling.software.proprietary.policy.store;
import java.io.Serializable;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
@@ -24,6 +28,8 @@ import stirling.software.proprietary.integration.crypto.LegacyDecryptStringConve
*/
@Entity
@Table(name = "policies")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "policies")
@NoArgsConstructor
@Getter
@Setter
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java
index 35987f0211..dee7803458 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java
@@ -19,7 +19,8 @@ import stirling.software.proprietary.model.ToolChainStatId;
* take the top N workflows without loading the table.
*/
@Repository
-public interface ToolChainStatRepository extends JpaRepository<ToolChainStat, ToolChainStatId> {
+public interface ToolChainStatRepository
+ extends JpaRepository<ToolChainStat, ToolChainStatId>, ToolChainStatRepositoryCustom {
String SELECT_TOP =
"SELECT c.chainKey, MAX(c.chainLength), SUM(c.count) FROM ToolChainStat c WHERE ";
@@ -65,25 +66,6 @@ public interface ToolChainStatRepository extends JpaRepository<ToolChainStat, To
@Param("epochDay") long epochDay,
@Param("delta") long delta);
- /**
- * Native insert so a concurrent first-run-of-day loses the primary key race instead of silently
- * overwriting the winner - {@code save()} would merge, resetting their count.
- */
- @Modifying(clearAutomatically = true)
- @Transactional
- @Query(
- value =
- "INSERT INTO tool_chain_stats (principal, chain_key, epoch_day, chain_length,"
- + " count) VALUES (:principal, :chainKey, :epochDay, :chainLength,"
- + " :delta)",
- nativeQuery = true)
- void insertCount(
- @Param("principal") String principal,
- @Param("chainKey") String chainKey,
- @Param("epochDay") long epochDay,
- @Param("chainLength") int chainLength,
- @Param("delta") long delta);
-
@Modifying(clearAutomatically = true)
@Transactional
@Query("DELETE FROM ToolChainStat c WHERE c.epochDay < :cutoff")
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustom.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustom.java
new file mode 100644
index 0000000000..2b936cf142
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustom.java
@@ -0,0 +1,10 @@
+package stirling.software.proprietary.repository;
+
+/**
+ * The day's-first tool-chain insert. A fragment rather than {@code save()} because a merge would
+ * overwrite the concurrent winner's row instead of losing the primary key race.
+ */
+public interface ToolChainStatRepositoryCustom {
+
+ void insertCount(String principal, String chainKey, long epochDay, int chainLength, long delta);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustomImpl.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustomImpl.java
new file mode 100644
index 0000000000..411cbbfc14
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepositoryCustomImpl.java
@@ -0,0 +1,25 @@
+package stirling.software.proprietary.repository;
+
+import org.springframework.transaction.annotation.Transactional;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+import stirling.software.proprietary.model.ToolChainStat;
+
+/** See {@link ToolChainStatRepositoryCustom}. */
+class ToolChainStatRepositoryCustomImpl implements ToolChainStatRepositoryCustom {
+
+ @PersistenceContext private EntityManager entityManager;
+
+ @Override
+ @Transactional
+ public void insertCount(
+ String principal, String chainKey, long epochDay, int chainLength, long delta) {
+ entityManager.persist(new ToolChainStat(principal, chainKey, epochDay, chainLength, delta));
+ // Flush so a losing racer's primary-key violation surfaces here, where the caller's catch
+ // falls back to incrementing the winner's row.
+ entityManager.flush();
+ entityManager.clear();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java
index d45e27a74e..6cc7708bbb 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java
@@ -23,7 +23,8 @@ import stirling.software.proprietary.model.ToolUsageStatId;
* - per distinct value a caller asks about, which is a scan the caller gets to trigger.
*/
@Repository
-public interface ToolUsageStatRepository extends JpaRepository<ToolUsageStat, ToolUsageStatId> {
+public interface ToolUsageStatRepository
+ extends JpaRepository<ToolUsageStat, ToolUsageStatId>, ToolUsageStatRepositoryCustom {
String RECENT = "SUM(CASE WHEN s.epochDay >= :recentCutoff THEN s.count ELSE 0 END), ";
@@ -94,24 +95,6 @@ public interface ToolUsageStatRepository extends JpaRepository<ToolUsageStat, To
@Param("epochDay") long epochDay,
@Param("delta") long delta);
- /**
- * Native insert so a concurrent first-run-of-day loses the primary key race instead of silently
- * overwriting the winner - {@code save()} would merge, resetting their count.
- */
- @Modifying(clearAutomatically = true)
- @Transactional
- @Query(
- value =
- "INSERT INTO tool_usage_stats (principal, from_tool, tool_key, epoch_day,"
- + " count) VALUES (:principal, :fromTool, :toolKey, :epochDay, :delta)",
- nativeQuery = true)
- void insertCount(
- @Param("principal") String principal,
- @Param("fromTool") String fromTool,
- @Param("toolKey") String toolKey,
- @Param("epochDay") long epochDay,
- @Param("delta") long delta);
-
@Modifying(clearAutomatically = true)
@Transactional
@Query("DELETE FROM ToolUsageStat s WHERE s.epochDay < :cutoff")
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustom.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustom.java
new file mode 100644
index 0000000000..6d63c97fe0
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustom.java
@@ -0,0 +1,10 @@
+package stirling.software.proprietary.repository;
+
+/**
+ * The day's-first tool-usage insert. A fragment rather than {@code save()} because a merge would
+ * overwrite the concurrent winner's row instead of losing the primary key race.
+ */
+public interface ToolUsageStatRepositoryCustom {
+
+ void insertCount(String principal, String fromTool, String toolKey, long epochDay, long delta);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustomImpl.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustomImpl.java
new file mode 100644
index 0000000000..d458171216
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepositoryCustomImpl.java
@@ -0,0 +1,25 @@
+package stirling.software.proprietary.repository;
+
+import org.springframework.transaction.annotation.Transactional;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+import stirling.software.proprietary.model.ToolUsageStat;
+
+/** See {@link ToolUsageStatRepositoryCustom}. */
+class ToolUsageStatRepositoryCustomImpl implements ToolUsageStatRepositoryCustom {
+
+ @PersistenceContext private EntityManager entityManager;
+
+ @Override
+ @Transactional
+ public void insertCount(
+ String principal, String fromTool, String toolKey, long epochDay, long delta) {
+ entityManager.persist(new ToolUsageStat(principal, fromTool, toolKey, epochDay, delta));
+ // Flush so a losing racer's primary-key violation surfaces here, where the caller's catch
+ // falls back to incrementing the winner's row.
+ entityManager.flush();
+ entityManager.clear();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java
index 36dcaecfd2..fb156d92e4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java
@@ -1,7 +1,10 @@
package stirling.software.proprietary.security.configuration;
import java.time.Duration;
+import java.util.Map;
+import org.hibernate.cfg.AvailableSettings;
+import org.springframework.boot.hibernate.autoconfigure.HibernatePropertiesCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
@@ -10,10 +13,13 @@ import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
+import lombok.extern.slf4j.Slf4j;
+
import stirling.software.common.model.ApplicationProperties;
@Configuration
@EnableCaching
+@Slf4j
public class CacheConfig {
private final ApplicationProperties applicationProperties;
@@ -44,4 +50,35 @@ public class CacheConfig {
.build());
return cacheManager;
}
+
+ /**
+ * Stands the second-level cache down when the process-local regions would be unsafe: cluster
+ * mode has more than one node behind the database, and an operator can rule the cache out
+ * explicitly for multi-instance setups that do not use cluster mode yet.
+ */
+ @Bean
+ HibernatePropertiesCustomizer hibernateSecondLevelCacheGate() {
+ return hibernateProperties -> {
+ if (applicationProperties.getCluster().isEnabled()) {
+ log.warn(
+ "cluster.enabled=true: disabling the Hibernate second-level cache because"
+ + " the Caffeine regions are process-local and cannot be invalidated"
+ + " across nodes. Security and licensing reads fall back to the"
+ + " database.");
+ disableSecondLevelCache(hibernateProperties);
+ return;
+ }
+ if (!applicationProperties.getSecondLevelCache().isEnabled()) {
+ log.info(
+ "secondLevelCache.enabled=false: Hibernate second-level cache disabled by"
+ + " configuration.");
+ disableSecondLevelCache(hibernateProperties);
+ }
+ };
+ }
+
+ private static void disableSecondLevelCache(Map<String, Object> hibernateProperties) {
+ hibernateProperties.put(AvailableSettings.USE_SECOND_LEVEL_CACHE, false);
+ hibernateProperties.put("jakarta.persistence.sharedCache.mode", "NONE");
+ }
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
index 4aa9d489a9..9b3c6d47a6 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java
@@ -18,7 +18,7 @@ import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.User;
-public interface UserRepository extends JpaRepository<User, Long> {
+public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom {
@Query(
"SELECT u FROM User u JOIN u.authorities a WHERE a.authority = 'ROLE_ADMIN' AND (u.enabled IS NULL OR u.enabled = true) ORDER BY u.id ASC")
List<User> findEnabledAdminsByIdAsc();
@@ -146,13 +146,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
+ "WHERE KEY(settings) = :key AND settings = :value")
long countUsersBySetting(@Param("key") String key, @Param("value") String value);
- @Modifying
- @Query(
- value = "DELETE FROM user_settings WHERE user_id = :userId AND setting_key IN (:keys)",
- nativeQuery = true)
- void deleteSettingsByUserIdAndKeys(
- @Param("userId") Long userId, @Param("keys") List<String> keys);
-
/** Anonymous users (no username) created before the cut-off, streamed for batch cleanup. */
@Query("SELECT u.id FROM User u WHERE u.username IS NULL AND u.createdAt < :cutoffDate")
Stream<Long> findByUsernameIsNullAndCreatedAtBefore(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustom.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustom.java
new file mode 100644
index 0000000000..edcfc012ac
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustom.java
@@ -0,0 +1,15 @@
+package stirling.software.proprietary.security.database.repository;
+
+import java.util.Optional;
+
+import stirling.software.proprietary.security.model.User;
+
+/** Lookups the caches answer without a SELECT once warm. */
+public interface UserRepositoryCustom {
+
+ /**
+ * Returns the user when the username resolves. Unlike the derived {@code findByUsername} query,
+ * this goes through the natural-id cache and the entity cache.
+ */
+ Optional<User> findByUsernameNatural(String username);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustomImpl.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustomImpl.java
new file mode 100644
index 0000000000..16169a5350
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepositoryCustomImpl.java
@@ -0,0 +1,25 @@
+package stirling.software.proprietary.security.database.repository;
+
+import java.util.Optional;
+
+import org.hibernate.KeyType;
+import org.hibernate.Session;
+import org.springframework.transaction.annotation.Transactional;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+import stirling.software.proprietary.security.model.User;
+
+/** See {@link UserRepositoryCustom}. */
+class UserRepositoryCustomImpl implements UserRepositoryCustom {
+
+ @PersistenceContext private EntityManager entityManager;
+
+ @Override
+ @Transactional(readOnly = true)
+ public Optional<User> findByUsernameNatural(String username) {
+ return Optional.ofNullable(
+ entityManager.unwrap(Session.class).find(User.class, username, KeyType.NATURAL));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/Authority.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/Authority.java
index 4ffea54740..8c52efc787 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/Authority.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/Authority.java
@@ -3,10 +3,13 @@ package stirling.software.proprietary.security.model;
import java.io.Serial;
import java.io.Serializable;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.security.core.GrantedAuthority;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -25,6 +28,8 @@ import lombok.Setter;
name = "authorities",
// index the FK: authorities load by user_id
indexes = @Index(name = "idx_authorities_user_id", columnList = "user_id"))
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
@Getter
@Setter
public class Authority implements GrantedAuthority, Serializable {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/User.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/User.java
index 9455ed6e4b..b29ceb00d1 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/model/User.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/model/User.java
@@ -5,7 +5,11 @@ import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.CreationTimestamp;
+import org.hibernate.annotations.NaturalId;
+import org.hibernate.annotations.NaturalIdCache;
import org.hibernate.annotations.UpdateTimestamp;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.security.core.userdetails.UserDetails;
@@ -24,6 +28,12 @@ import stirling.software.proprietary.model.Team;
name = "users",
// team_id backs Team.users joins, the admin roster fetch, and per-team user counts.
indexes = @Index(name = "idx_users_team_id", columnList = "team_id"))
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
+// Explicit region: the default EntityName##NaturalId contains '#' which the
+// caffeine-jcache provider cannot resolve (it concatenates the name into an
+// unquoted Typesafe Config path, where '#' starts a comment).
+@NaturalIdCache(region = "usersNaturalId")
@NoArgsConstructor
@Getter
@Setter
@@ -37,6 +47,8 @@ public class User implements UserDetails, Serializable {
@Column(name = "user_id")
private Long id;
+ // Mutable: changeUsername renames users, so the natural-id mapping must follow renames.
+ @NaturalId(mutable = true)
@Column(name = "username", unique = true)
private String username;
@@ -87,6 +99,7 @@ public class User implements UserDetails, Serializable {
@Column(name = "supabase_auth_id", unique = true)
private UUID supabaseId;
+ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Set<Authority> authorities = new HashSet<>();
@@ -94,6 +107,7 @@ public class User implements UserDetails, Serializable {
@JoinColumn(name = "team_id")
private Team team;
+ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
@ElementCollection
@MapKeyColumn(name = "setting_key")
@Column(name = "setting_value", columnDefinition = "text")
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java
index 99e87a82b8..e5abb22685 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/CustomUserDetailsService.java
@@ -29,7 +29,7 @@ public class CustomUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user =
userRepository
- .findByUsername(username)
+ .findByUsernameNatural(username)
.orElseThrow(
() ->
new UsernameNotFoundException(
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/MfaService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/MfaService.java
index f8a558ecff..7396506f5e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/MfaService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/MfaService.java
@@ -1,7 +1,6 @@
package stirling.software.proprietary.security.service;
import java.sql.SQLException;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -69,16 +68,11 @@ public class MfaService {
User managedUser = getUserWithSettings(user);
Map<String, String> settings = ensureSettings(managedUser);
settings.put(MFA_ENABLED_KEY, "false");
- // Clear existing values and flush the removals before inserting a new secret. This keeps
- // the (user_id, setting_key) PK satisfied even when the persistence context re-inserts the
- // same keys within a single transaction.
+ // Flush the removals before the re-insert below: Hibernate executes a collection's removals
+ // before its additions, so the (user_id, setting_key) primary key stays satisfied.
settings.remove(MFA_SECRET_KEY);
settings.remove(MFA_LAST_USED_STEP_KEY);
- if (managedUser != null && managedUser.getId() != null) {
- userRepository.deleteSettingsByUserIdAndKeys(
- managedUser.getId(), Arrays.asList(MFA_SECRET_KEY, MFA_LAST_USED_STEP_KEY));
- userRepository.flush();
- }
+ userRepository.flush();
settings.put(MFA_SECRET_KEY, secret);
persist(managedUser);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
index 7ae07be5b4..b9b038cacd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
@@ -16,6 +16,8 @@ import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
+import org.hibernate.KeyType;
+import org.hibernate.Session;
import org.slf4j.MDC;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.MessageSource;
@@ -34,6 +36,8 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
+import jakarta.persistence.EntityManager;
+
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -78,6 +82,7 @@ import stirling.software.proprietary.workflow.service.UserServerCertificateServi
public class UserService implements UserServiceInterface {
private final UserRepository userRepository;
+ private final EntityManager entityManager;
private final stirling.software.proprietary.service.OrgOwnerService orgOwnerService;
private final TeamRepository teamRepository;
private final AuthorityRepository authorityRepository;
@@ -385,8 +390,10 @@ public class UserService implements UserServiceInterface {
}
}
+ @Transactional(readOnly = true)
public Optional<User> findByUsername(String username) {
- return userRepository.findByUsername(username);
+ User user = entityManager.unwrap(Session.class).find(User.class, username, KeyType.NATURAL);
+ return Optional.ofNullable(user);
}
/** Resolves a user by Supabase auth UUID; empty for rows with no supabase_id. */
diff --git a/app/proprietary/src/main/resources/application-security.properties b/app/proprietary/src/main/resources/application-security.properties
new file mode 100644
index 0000000000..98c388c032
--- /dev/null
+++ b/app/proprietary/src/main/resources/application-security.properties
@@ -0,0 +1,18 @@
+# Hibernate L2 Caching with Caffeine / JCache
+# Scoped to the "security" profile, which SPDFApplication activates exactly when the
+# :proprietary module is on the classpath (STIRLING_FLAVOR=proprietary/saas). Core-only builds
+# (STIRLING_FLAVOR=core / DISABLE_ADDITIONAL_FEATURES=true) never activate this profile and never
+# ship hibernate-jcache + caffeine, so the JCache classes below must not be referenced by default
+# config that a core runtime reads.
+spring.jpa.properties.hibernate.cache.use_second_level_cache=true
+spring.jpa.properties.hibernate.cache.use_query_cache=false
+spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.internal.JCacheRegionFactory
+spring.jpa.properties.hibernate.javax.cache.provider=com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider
+# Fail on a region that has no explicit application.conf entry instead of the default
+# create-warn, which Hibernate docs (User Guide 14.10.3) warn "may not be suitable for production
+# usage (unlimited size and no eviction in particular)". Every @Cacheable entity/collection must
+# have a matching caffeine.jcache region block; otherwise startup fails loudly here.
+spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=fail
+# Hibernate statistics tracking has per-operation overhead; the L2 cache test enables it on demand.
+spring.jpa.properties.hibernate.generate_statistics=false
+spring.jpa.properties.jakarta.persistence.sharedCache.mode=ENABLE_SELECTIVE
diff --git a/app/proprietary/src/main/resources/application.conf b/app/proprietary/src/main/resources/application.conf
new file mode 100644
index 0000000000..290f65b26d
--- /dev/null
+++ b/app/proprietary/src/main/resources/application.conf
@@ -0,0 +1,151 @@
+# Per-region policies for the Caffeine JCache caches backing Hibernate's second-level cache.
+#
+# The schema below follows the caffeine-jcache provider's own reference.conf (shipped in the
+# jcache jar): bounded size is `policy.maximum.size`, expiry is `policy.eager-expiration.after-write`
+# and statistics is `monitoring.statistics`. Keys written against any other schema (e.g.
+# `policy.maximum` / `policy.expire-after-write` / `statistics-enabled`) are silently ignored by
+# the provider and the region falls back to unbounded, eternal-expiry Caffeine defaults.
+#
+# Region names match the `@Cache(region = "...")` values on the cached entities. A region shared by
+# an entity and its collections (e.g. "users") maps to one Caffeine cache.
+caffeine.jcache {
+ default {
+ policy {
+ maximum {
+ size = 500
+ }
+ eager-expiration {
+ after-write = 15m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ policies {
+ policy {
+ maximum {
+ size = 500
+ }
+ eager-expiration {
+ after-write = 30m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ policy-sources {
+ policy {
+ maximum {
+ size = 500
+ }
+ eager-expiration {
+ after-write = 30m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ teams {
+ policy {
+ maximum {
+ size = 1000
+ }
+ eager-expiration {
+ after-write = 15m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ user-license-settings {
+ policy {
+ maximum {
+ size = 2000
+ }
+ eager-expiration {
+ after-write = 1h
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ users {
+ policy {
+ maximum {
+ size = 5000
+ }
+ eager-expiration {
+ after-write = 5m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ usersNaturalId {
+ policy {
+ maximum {
+ size = 5000
+ }
+ eager-expiration {
+ after-write = 5m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ saas-pricing-policies {
+ policy {
+ maximum {
+ size = 100
+ }
+ eager-expiration {
+ after-write = 30s
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ saas-legal-consents {
+ policy {
+ maximum {
+ size = 5000
+ }
+ eager-expiration {
+ after-write = 1h
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+
+ saas-subscriptions {
+ policy {
+ maximum {
+ size = 5000
+ }
+ eager-expiration {
+ after-write = 15m
+ }
+ }
+ monitoring {
+ statistics = true
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/cache/CaffeineJCacheConfigTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/cache/CaffeineJCacheConfigTest.java
new file mode 100644
index 0000000000..02cc21b30b
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/cache/CaffeineJCacheConfigTest.java
@@ -0,0 +1,100 @@
+package stirling.software.proprietary.cache;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.net.URI;
+import java.time.Duration;
+import java.util.stream.Stream;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.CompleteConfiguration;
+import javax.cache.spi.CachingProvider;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import com.github.benmanes.caffeine.jcache.configuration.CaffeineConfiguration;
+import com.typesafe.config.ConfigFactory;
+
+/**
+ * Guards the wiring between the Caffeine/JCache provider and its {@code application.conf} resource.
+ * The provider locates the {@code caffeine.jcache} root through Typesafe Config's {@code
+ * ConfigFactory.load()}, and Hibernate's {@code JCacheRegionFactory} requests each region by name
+ * from the resulting {@link CacheManager}. If {@code application.conf} ever stops being on the
+ * runtime classpath (it lives in the :proprietary module), the per-region policies silently fall
+ * back to Caffeine defaults and the bounded/TTL'd cache guarantees are lost - this test pins the
+ * contract.
+ */
+class CaffeineJCacheConfigTest {
+
+ /**
+ * Own URI so this test never shares Hibernate's default cache manager: the provider reuses
+ * managers by URI, and closing the shared one would pull it out from under an active
+ * persistence context.
+ */
+ private static final URI TEST_CACHE_MANAGER_URI =
+ URI.create("stirling.software.proprietary.cache.CaffeineJCacheConfigTest");
+
+ @Test
+ void applicationConfIsOnTheClasspath() {
+ var config = ConfigFactory.load(getClass().getClassLoader());
+ assertThat(config.hasPath("caffeine.jcache")).isTrue();
+ assertThat(config.getInt("caffeine.jcache.users.policy.maximum.size")).isEqualTo(5000);
+ assertThat(config.getString("caffeine.jcache.users.policy.eager-expiration.after-write"))
+ .isEqualTo("5m");
+ }
+
+ /**
+ * Every region named by an entity {@code @Cache} must resolve to the bounded, TTL'd policy from
+ * {@code application.conf}. A misspelled expiry key would otherwise fall back to Caffeine's
+ * unbounded, eternal defaults for that region while the config file looks correct.
+ */
+ static Stream<Arguments> regions() {
+ return Stream.of(
+ Arguments.of("policies", 500L, Duration.ofMinutes(30)),
+ Arguments.of("policy-sources", 500L, Duration.ofMinutes(30)),
+ Arguments.of("teams", 1000L, Duration.ofMinutes(15)),
+ Arguments.of("user-license-settings", 2000L, Duration.ofHours(1)),
+ Arguments.of("users", 5000L, Duration.ofMinutes(5)),
+ Arguments.of("usersNaturalId", 5000L, Duration.ofMinutes(5)),
+ Arguments.of("saas-pricing-policies", 100L, Duration.ofSeconds(30)),
+ Arguments.of("saas-legal-consents", 5000L, Duration.ofHours(1)),
+ Arguments.of("saas-subscriptions", 5000L, Duration.ofMinutes(15)));
+ }
+
+ @ParameterizedTest(name = "{0} applies its configured bounds")
+ @MethodSource("regions")
+ void everyRegionAppliesItsConfiguredPolicy(
+ String region, long maximumSize, Duration expireAfterWrite) {
+ assertRegionPolicy(region, maximumSize, expireAfterWrite);
+ }
+
+ private static void assertRegionPolicy(
+ String region, long maximumSize, Duration expireAfterWrite) {
+ CachingProvider provider =
+ Caching.getCachingProvider(
+ "com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider");
+ try (CacheManager manager =
+ provider.getCacheManager(
+ TEST_CACHE_MANAGER_URI, provider.getDefaultClassLoader())) {
+ Cache<?, ?> cache = manager.getCache(region);
+ assertThat(cache)
+ .as("region <%s> is created from application.conf", region)
+ .isNotNull();
+
+ CaffeineConfiguration<?, ?> configuration =
+ (CaffeineConfiguration<?, ?>)
+ cache.getConfiguration(CompleteConfiguration.class);
+ assertThat(configuration.getMaximumSize())
+ .as("region <%s> maximum size", region)
+ .hasValue(maximumSize);
+ assertThat(configuration.getExpireAfterWrite())
+ .as("region <%s> expire-after-write", region)
+ .hasValue(expireAfterWrite.toNanos());
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/cache/HibernateSecondLevelCacheTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/cache/HibernateSecondLevelCacheTest.java
new file mode 100644
index 0000000000..ea651dc058
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/cache/HibernateSecondLevelCacheTest.java
@@ -0,0 +1,429 @@
+package stirling.software.proprietary.cache;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.LocalDate;
+import java.time.ZoneOffset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.hibernate.KeyType;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.stat.Statistics;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.boot.persistence.autoconfigure.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.policy.store.PolicyEntity;
+import stirling.software.proprietary.policy.store.PolicyRepository;
+import stirling.software.proprietary.repository.ToolUsageStatRepository;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamRepository;
+
+@DataJpaTest(
+ properties = {
+ "spring.jpa.properties.hibernate.cache.use_second_level_cache=true",
+ "spring.jpa.properties.hibernate.cache.use_query_cache=false",
+ "spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.internal.JCacheRegionFactory",
+ "spring.jpa.properties.hibernate.javax.cache.provider=com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider",
+ "spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=fail",
+ "spring.jpa.properties.hibernate.generate_statistics=true",
+ "spring.jpa.properties.jakarta.persistence.sharedCache.mode=ENABLE_SELECTIVE"
+ })
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class HibernateSecondLevelCacheTest {
+
+ @Autowired private PolicyRepository policyRepository;
+
+ @Autowired private UserRepository userRepository;
+
+ @Autowired private TeamRepository teamRepository;
+
+ @Autowired private ToolUsageStatRepository toolUsageStatRepository;
+
+ @Autowired private EntityManagerFactory entityManagerFactory;
+
+ @Autowired private EntityManager entityManager;
+
+ @Autowired private PlatformTransactionManager transactionManager;
+
+ private SessionFactory sessionFactory;
+ private Statistics statistics;
+ private TransactionTemplate txTemplate;
+
+ @BeforeEach
+ void setUp() {
+ sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
+ statistics = sessionFactory.getStatistics();
+ statistics.setStatisticsEnabled(true);
+ txTemplate = new TransactionTemplate(transactionManager);
+ statistics.clear();
+ }
+
+ @Test
+ void testSecondLevelCacheHitOnEntityFind() {
+ // Step 1: Save entity in Transaction 1 (commits and puts into L2 cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity policy = new PolicyEntity();
+ policy.setId("cache-test-policy-1");
+ policy.setName("Cache Test Policy");
+ policy.setEnabled(true);
+ policy.setOwner("admin");
+ policyRepository.save(policy);
+ });
+
+ long hitsBefore = statistics.getSecondLevelCacheHitCount();
+
+ // Step 2: Read entity in Transaction 2 (should hit L2 cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity loaded =
+ policyRepository.findById("cache-test-policy-1").orElseThrow();
+ assertThat(loaded.getName()).isEqualTo("Cache Test Policy");
+ });
+
+ long hitsAfter = statistics.getSecondLevelCacheHitCount();
+ assertThat(hitsAfter).isGreaterThan(hitsBefore);
+ }
+
+ @Test
+ void testSecondLevelCacheEvictionOnEntityUpdate() {
+ // Step 1: Save entity in Transaction 1
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity policy = new PolicyEntity();
+ policy.setId("cache-test-policy-2");
+ policy.setName("Initial Name");
+ policy.setEnabled(true);
+ policy.setOwner("admin");
+ policyRepository.save(policy);
+ });
+
+ // Step 2: Read in Transaction 2 (populates/hits L2 cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity loaded =
+ policyRepository.findById("cache-test-policy-2").orElseThrow();
+ assertThat(loaded.getName()).isEqualTo("Initial Name");
+ });
+
+ // Step 3: Update entity in Transaction 3 (evicts/updates L2 cache on commit)
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity toUpdate =
+ policyRepository.findById("cache-test-policy-2").orElseThrow();
+ toUpdate.setName("Updated Name");
+ policyRepository.save(toUpdate);
+ });
+
+ // Step 4: Read after update in Transaction 4 (reflects updated state)
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity reloaded =
+ policyRepository.findById("cache-test-policy-2").orElseThrow();
+ assertThat(reloaded.getName()).isEqualTo("Updated Name");
+ });
+ }
+
+ @Test
+ void testSecondLevelCacheEvictedByBulkHqlUpdate() {
+ String id = "cache-test-policy-bulk";
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ PolicyEntity policy = new PolicyEntity();
+ policy.setId(id);
+ policy.setName("Bulk Initial");
+ policy.setEnabled(true);
+ policy.setOwner("admin");
+ policyRepository.save(policy);
+ });
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ assertThat(policyRepository.findById(id).orElseThrow().getName())
+ .isEqualTo("Bulk Initial");
+ });
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ try (EntityManager em = entityManagerFactory.createEntityManager()) {
+ em.getTransaction().begin();
+ em.createQuery(
+ "update PolicyEntity p set p.name = 'Bulk Updated' where"
+ + " p.id = :id")
+ .setParameter("id", id)
+ .executeUpdate();
+ em.getTransaction().commit();
+ }
+ });
+
+ // Hibernate's BulkOperationCleanupAction evicts the region on the bulk HQL update, so the
+ // next read must observe the new value rather than the stale second-level cache entry.
+ txTemplate.executeWithoutResult(
+ status -> {
+ assertThat(policyRepository.findById(id).orElseThrow().getName())
+ .isEqualTo("Bulk Updated");
+ });
+ }
+
+ @Test
+ void testUserAndTeamSecondLevelCacheAndEviction() {
+ AtomicReference<Long> userIdRef = new AtomicReference<>();
+ AtomicReference<Long> teamIdRef = new AtomicReference<>();
+
+ // Save Team and User in Transaction 1
+ txTemplate.executeWithoutResult(
+ status -> {
+ Team team = new Team();
+ team.setName("Cache Team");
+ team = teamRepository.save(team);
+ teamIdRef.set(team.getId());
+
+ User user = new User();
+ user.setUsername("cacheuser");
+ user.setPassword("secret123");
+ user.setTeam(team);
+ user = userRepository.save(user);
+ userIdRef.set(user.getId());
+ });
+
+ // Read user by ID in Transaction 2 (loads and populates L2 cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ User loaded = userRepository.findById(userIdRef.get()).orElseThrow();
+ assertThat(loaded.getUsername()).isEqualTo("cacheuser");
+ });
+
+ long hitsBefore = statistics.getSecondLevelCacheHitCount();
+
+ // Read user by ID in Transaction 3 (must HIT L2 cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ User loaded = userRepository.findById(userIdRef.get()).orElseThrow();
+ assertThat(loaded.getUsername()).isEqualTo("cacheuser");
+ });
+
+ long hitsAfter = statistics.getSecondLevelCacheHitCount();
+ assertThat(hitsAfter).isGreaterThan(hitsBefore);
+
+ // The team side of the mapping gets the same treatment: read in a fresh transaction,
+ // re-read for an L2 hit, then prove explicit eviction drops it.
+ txTemplate.executeWithoutResult(
+ status -> {
+ Team loaded = teamRepository.findById(teamIdRef.get()).orElseThrow();
+ assertThat(loaded.getName()).isEqualTo("Cache Team");
+ });
+
+ long teamHitsBefore = statistics.getSecondLevelCacheHitCount();
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ Team loaded = teamRepository.findById(teamIdRef.get()).orElseThrow();
+ assertThat(loaded.getName()).isEqualTo("Cache Team");
+ });
+
+ assertThat(statistics.getSecondLevelCacheHitCount()).isGreaterThan(teamHitsBefore);
+
+ entityManagerFactory.getCache().evict(Team.class, teamIdRef.get());
+ assertThat(entityManagerFactory.getCache().contains(Team.class, teamIdRef.get())).isFalse();
+
+ // Explicit eviction test
+ entityManagerFactory.getCache().evict(User.class, userIdRef.get());
+
+ // Check cache does not contain user after explicit eviction
+ assertThat(entityManagerFactory.getCache().contains(User.class, userIdRef.get())).isFalse();
+ }
+
+ @Test
+ void testNaturalIdCacheHitOnUsernameLookup() {
+ // Save user in Transaction 1
+ txTemplate.executeWithoutResult(
+ status -> {
+ User user = new User();
+ user.setUsername("naturaliduser");
+ user.setPassword("secret123");
+ userRepository.save(user);
+ });
+
+ // Resolve by natural ID in Transaction 2 (populates the natural-ID cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ User loaded =
+ entityManager
+ .unwrap(Session.class)
+ .find(User.class, "naturaliduser", KeyType.NATURAL);
+ assertThat(loaded).isNotNull();
+ assertThat(loaded.getUsername()).isEqualTo("naturaliduser");
+ });
+
+ long hitsBefore = statistics.getNaturalIdCacheHitCount();
+
+ // Resolve again in Transaction 3 (must HIT the natural-ID cache)
+ txTemplate.executeWithoutResult(
+ status -> {
+ User loaded =
+ entityManager
+ .unwrap(Session.class)
+ .find(User.class, "naturaliduser", KeyType.NATURAL);
+ assertThat(loaded).isNotNull();
+ assertThat(loaded.getUsername()).isEqualTo("naturaliduser");
+ });
+
+ assertThat(statistics.getNaturalIdCacheHitCount()).isGreaterThan(hitsBefore);
+ }
+
+ /**
+ * Usage tallies are written on almost every tool run: those writes must not disturb the user
+ * region, and an edited settings collection must be reloaded rather than served from cache.
+ */
+ @Test
+ void ormWritesKeepUnrelatedRegionsAndReloadEditedSettings() {
+ AtomicReference<Long> userIdRef = new AtomicReference<>();
+ txTemplate.executeWithoutResult(
+ status -> {
+ User user = new User();
+ user.setUsername("orm-writes-user");
+ user.setPassword("secret123");
+ Map<String, String> settings = new HashMap<>();
+ settings.put("language", "en");
+ settings.put("mfaSecret", "topsecret");
+ user.setSettings(settings);
+ userIdRef.set(userRepository.save(user).getId());
+ });
+
+ txTemplate.executeWithoutResult(
+ status -> userRepository.findById(userIdRef.get()).orElseThrow());
+ assertThat(entityManagerFactory.getCache().contains(User.class, userIdRef.get())).isTrue();
+
+ long day = LocalDate.now(ZoneOffset.UTC).toEpochDay();
+ txTemplate.executeWithoutResult(
+ status ->
+ toolUsageStatRepository.insertCount(
+ "orm-writes-user", "compare", "ocr", day, 1));
+
+ assertThat(entityManagerFactory.getCache().contains(User.class, userIdRef.get()))
+ .as("a tool-usage insert must not evict cached users")
+ .isTrue();
+
+ // settings edit in the shape MfaService.setSecret uses: remove, flush, re-insert
+ txTemplate.executeWithoutResult(
+ status -> {
+ User managed = userRepository.findById(userIdRef.get()).orElseThrow();
+ managed.getSettings().remove("mfaSecret");
+ userRepository.flush();
+ });
+
+ assertThat(entityManagerFactory.getCache().contains(User.class, userIdRef.get()))
+ .as("a settings edit must not evict the user entity")
+ .isTrue();
+ txTemplate.executeWithoutResult(
+ status -> {
+ User reloaded = userRepository.findById(userIdRef.get()).orElseThrow();
+ assertThat(reloaded.getSettings())
+ .as("deleted setting must not be served from the cached collection")
+ .doesNotContainKey("mfaSecret");
+ assertThat(reloaded.getSettings()).containsEntry("language", "en");
+ });
+ }
+
+ /**
+ * The username natural id is mutable: the cached mapping must follow a rename, and the released
+ * username must be reusable by another account.
+ */
+ @Test
+ void mutableNaturalIdRenameTracksOldAndNewUsername() {
+ AtomicReference<Long> renamedId = new AtomicReference<>();
+ txTemplate.executeWithoutResult(
+ status -> {
+ User user = new User();
+ user.setUsername("rename-old-name");
+ user.setPassword("secret123");
+ renamedId.set(userRepository.save(user).getId());
+ });
+ txTemplate.executeWithoutResult(
+ status -> userRepository.findByUsernameNatural("rename-old-name").orElseThrow());
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ User managed = userRepository.findById(renamedId.get()).orElseThrow();
+ managed.setUsername("rename-new-name");
+ userRepository.flush();
+ });
+
+ txTemplate.executeWithoutResult(
+ status ->
+ assertThat(userRepository.findByUsernameNatural("rename-old-name"))
+ .as("the released username must stop resolving after the rename")
+ .isEmpty());
+ txTemplate.executeWithoutResult(
+ status ->
+ assertThat(userRepository.findByUsernameNatural("rename-new-name"))
+ .map(User::getId)
+ .contains(renamedId.get()));
+
+ AtomicReference<Long> claimerId = new AtomicReference<>();
+ txTemplate.executeWithoutResult(
+ status -> {
+ User claimer = new User();
+ claimer.setUsername("rename-old-name");
+ claimer.setPassword("secret123");
+ claimerId.set(userRepository.save(claimer).getId());
+ });
+ txTemplate.executeWithoutResult(
+ status ->
+ assertThat(userRepository.findByUsernameNatural("rename-old-name"))
+ .as("the released username must resolve to the new holder")
+ .map(User::getId)
+ .contains(claimerId.get()));
+ }
+
+ /** The per-request login/JWT lookup must run no SQL once both caches are warm. */
+ @Test
+ void warmNaturalIdLookupRunsNoSql() {
+ AtomicReference<Long> userId = new AtomicReference<>();
+ txTemplate.executeWithoutResult(
+ status -> {
+ User user = new User();
+ user.setUsername("no-sql-user");
+ user.setPassword("secret123");
+ userId.set(userRepository.save(user).getId());
+ });
+ txTemplate.executeWithoutResult(
+ status -> userRepository.findByUsernameNatural("no-sql-user").orElseThrow());
+
+ statistics.clear();
+ txTemplate.executeWithoutResult(
+ status ->
+ assertThat(userRepository.findByUsernameNatural("no-sql-user"))
+ .map(User::getId)
+ .contains(userId.get()));
+
+ assertThat(statistics.getPrepareStatementCount())
+ .as("a warm natural-id lookup is answered entirely from the caches")
+ .isZero();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ @EntityScan(basePackages = "stirling.software.proprietary")
+ @EnableJpaRepositories(basePackages = "stirling.software.proprietary")
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/HibernateSecondLevelCacheGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/HibernateSecondLevelCacheGateTest.java
new file mode 100644
index 0000000000..a1275caa00
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/HibernateSecondLevelCacheGateTest.java
@@ -0,0 +1,61 @@
+package stirling.software.proprietary.security.configuration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.common.model.ApplicationProperties;
+
+/**
+ * Pins the second-level cache gate: the process-local regions cannot be invalidated across nodes,
+ * so a clustered deployment must stand the cache down, and a multi-instance deployment that does
+ * not use cluster mode yet must be able to rule it out explicitly.
+ */
+class HibernateSecondLevelCacheGateTest {
+
+ private static Map<String, Object> customize(ApplicationProperties properties) {
+ Map<String, Object> hibernateProperties = new HashMap<>();
+ new CacheConfig(properties).hibernateSecondLevelCacheGate().customize(hibernateProperties);
+ return hibernateProperties;
+ }
+
+ @Test
+ void disablesSecondLevelCacheWhenClusterIsEnabled() {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getCluster().setEnabled(true);
+
+ assertThat(customize(properties))
+ .containsEntry("hibernate.cache.use_second_level_cache", false)
+ .containsEntry("jakarta.persistence.sharedCache.mode", "NONE");
+ }
+
+ @Test
+ void disablesSecondLevelCacheWhenTurnedOffExplicitly() {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSecondLevelCache().setEnabled(false);
+
+ assertThat(customize(properties))
+ .containsEntry("hibernate.cache.use_second_level_cache", false)
+ .containsEntry("jakarta.persistence.sharedCache.mode", "NONE");
+ }
+
+ @Test
+ void clusterModeWinsWhenSecondLevelCacheIsTurnedOnExplicitly() {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getCluster().setEnabled(true);
+ properties.getSecondLevelCache().setEnabled(true);
+
+ assertThat(customize(properties))
+ .containsEntry("hibernate.cache.use_second_level_cache", false);
+ }
+
+ @Test
+ void leavesSecondLevelCacheAloneForSingleNodeDeployments() {
+ ApplicationProperties properties = new ApplicationProperties();
+
+ assertThat(customize(properties)).isEmpty();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
index 23f1b50526..f3e3ef7fd5 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceMoreTest.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.security.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -13,6 +14,8 @@ import java.util.Map;
import java.util.Optional;
import java.util.UUID;
+import org.hibernate.KeyType;
+import org.hibernate.Session;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
@@ -30,6 +33,8 @@ import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
+import jakarta.persistence.EntityManager;
+
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
@@ -56,6 +61,7 @@ import stirling.software.proprietary.workflow.service.UserServerCertificateServi
class UserServiceMoreTest {
@Mock private UserRepository userRepository;
+ @Mock private EntityManager entityManager;
@Mock private TeamRepository teamRepository;
@Mock private AuthorityRepository authorityRepository;
@Mock private PasswordEncoder passwordEncoder;
@@ -159,7 +165,10 @@ class UserServiceMoreTest {
@Test
@DisplayName("usernameExists true when found")
void usernameExists() {
- when(userRepository.findByUsername("a")).thenReturn(Optional.of(user("a")));
+ User found = user("a");
+ Session session = mock(Session.class);
+ when(entityManager.unwrap(Session.class)).thenReturn(session);
+ when(session.find(User.class, "a", KeyType.NATURAL)).thenReturn(found);
assertThat(userService.usernameExists("a")).isTrue();
}
diff --git a/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java b/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java
index d57f0a8e42..dbe114afeb 100644
--- a/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java
+++ b/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java
@@ -4,9 +4,12 @@ import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
+import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@@ -22,6 +25,8 @@ import lombok.Setter;
*/
@Entity
@Table(name = "billing_subscriptions", schema = "public")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "saas-subscriptions")
@NoArgsConstructor
@Getter
@Setter
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
index 5698133fe8..f4c9a1aa77 100644
--- a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
@@ -3,8 +3,11 @@ package stirling.software.saas.legal;
import java.io.Serializable;
import java.time.LocalDateTime;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.CreationTimestamp;
+import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -25,6 +28,8 @@ import lombok.Setter;
*/
@Entity
@Table(name = "legal_consent")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "saas-legal-consents")
@NoArgsConstructor
@Getter
@Setter
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
index 5e668e89d8..cc814189c9 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
@@ -7,8 +7,11 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.CreationTimestamp;
+import jakarta.persistence.Cacheable;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
@@ -38,6 +41,8 @@ import stirling.software.saas.payg.model.JobSource;
*/
@Entity
@Table(name = "pricing_policy")
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "saas-pricing-policies")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@@ -93,6 +98,7 @@ public class PricingPolicy implements Serializable {
* <p>Persisted as a normalized child table {@code pricing_policy_step_limit (policy_id,
* job_source, step_limit)} rather than JSONB — values are typed and queryable directly.
*/
+ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "saas-pricing-policies")
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(
name = "pricing_policy_step_limit",
@@ -115,6 +121,7 @@ public class PricingPolicy implements Serializable {
*
* <p>Persisted as {@code pricing_policy_stripe_price (policy_id, stripe_price_id)}.
*/
+ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "saas-pricing-policies")
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(
name = "pricing_policy_stripe_price",
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepository.java
index d9d74feb79..c71d9b1f97 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepository.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepository.java
@@ -2,7 +2,6 @@ package stirling.software.saas.payg.repository;
import java.time.LocalDateTime;
import java.util.List;
-import java.util.UUID;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -13,28 +12,8 @@ import org.springframework.transaction.annotation.Transactional;
import stirling.software.saas.payg.meter.PaygMeterEventLog;
-public interface PaygMeterEventLogRepository extends JpaRepository<PaygMeterEventLog, Long> {
-
- /**
- * Idempotent pending insert. The two meter triggers (charge-completion + stale-close) share the
- * idempotency key, and a reconcile retry re-runs the same path, so {@code ON CONFLICT DO
- * NOTHING} keeps the audit row at exactly one per key. {@code occurred_at} defaults to {@code
- * CURRENT_TIMESTAMP} at the DB; {@code posted_to_stripe_at} stays NULL until success.
- * Transactional because it's called from the non-transactional meter-reporting path.
- */
- @Transactional
- @Modifying
- @Query(
- value =
- "INSERT INTO payg_meter_event_log (team_id, job_id, idempotency_key, units)"
- + " VALUES (:teamId, :jobId, :key, :units)"
- + " ON CONFLICT (idempotency_key) DO NOTHING",
- nativeQuery = true)
- void insertPending(
- @Param("teamId") Long teamId,
- @Param("jobId") UUID jobId,
- @Param("key") String key,
- @Param("units") int units);
+public interface PaygMeterEventLogRepository
+ extends JpaRepository<PaygMeterEventLog, Long>, PaygMeterEventLogRepositoryCustom {
/** Stamp an event posted; clears any prior error. No-op if already posted. */
@Transactional
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustom.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustom.java
new file mode 100644
index 0000000000..88c3bea1ab
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustom.java
@@ -0,0 +1,14 @@
+package stirling.software.saas.payg.repository;
+
+import java.util.UUID;
+
+/**
+ * The idempotent meter-log insert: {@code ON CONFLICT (idempotency_key) DO NOTHING} collapses the
+ * two meter triggers and reconcile retries to one row without an exception, which an ORM insert
+ * cannot preserve. Declares its table so the commit scopes cache invalidation to {@code
+ * payg_meter_event_log} instead of discarding every region.
+ */
+public interface PaygMeterEventLogRepositoryCustom {
+
+ void insertPending(Long teamId, UUID jobId, String key, int units);
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustomImpl.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustomImpl.java
new file mode 100644
index 0000000000..b06b7e3ee7
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygMeterEventLogRepositoryCustomImpl.java
@@ -0,0 +1,41 @@
+package stirling.software.saas.payg.repository;
+
+import java.util.UUID;
+
+import org.hibernate.query.NativeQuery;
+import org.springframework.transaction.annotation.Transactional;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+/** See {@link PaygMeterEventLogRepositoryCustom}. */
+class PaygMeterEventLogRepositoryCustomImpl implements PaygMeterEventLogRepositoryCustom {
+
+ @PersistenceContext private EntityManager entityManager;
+
+ /**
+ * Idempotent pending insert. The two meter triggers (charge-completion + stale-close) share the
+ * idempotency key, and a reconcile retry re-runs the same path, so {@code ON CONFLICT DO
+ * NOTHING} keeps the audit row at exactly one per key. {@code occurred_at} defaults to {@code
+ * CURRENT_TIMESTAMP} at the DB; {@code posted_to_stripe_at} stays NULL until success.
+ * Transactional because it's called from the non-transactional meter-reporting path.
+ */
+ @Override
+ @Transactional
+ public void insertPending(Long teamId, UUID jobId, String key, int units) {
+ entityManager
+ .createNativeQuery(
+ "INSERT INTO payg_meter_event_log (team_id, job_id, idempotency_key,"
+ + " units) VALUES (:teamId, :jobId, :key, :units) ON CONFLICT"
+ + " (idempotency_key) DO NOTHING")
+ .setParameter("teamId", teamId)
+ .setParameter("jobId", jobId)
+ .setParameter("key", key)
+ .setParameter("units", units)
+ .unwrap(NativeQuery.class)
+ // The insert writes only payg_meter_event_log; see
+ // PaygMeterEventLogRepositoryCustom.
+ .addSynchronizedQuerySpace("payg_meter_event_log")
+ .executeUpdate();
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
index 3be0f13d68..eae5edf602 100644
--- a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
@@ -9,7 +9,8 @@ import org.springframework.data.repository.query.Param;
import stirling.software.saas.model.SaasTeamExtensions;
-public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExtensions, Long> {
+public interface SaasTeamExtensionsRepository
+ extends JpaRepository<SaasTeamExtensions, Long>, SaasTeamExtensionsRepositoryCustom {
// A linked team needs one cloud owner even when everyone works on its self-hosted deployments.
String CLOUD_SEATS =
@@ -29,21 +30,6 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExte
Optional<SaasTeamExtensions> findByTeamId(Long teamId);
- /**
- * Atomic seat claim for every team type. Returns 1 on success, 0 when capacity is exhausted.
- */
- @Modifying
- @Query(
- value =
- "UPDATE stirling_pdf.saas_team_extensions e SET seats_used = seats_used + 1 "
- + "WHERE team_id = :teamId AND ("
- + FLEET_SEATS
- + " < max_seats OR "
- + ENTERPRISE_ACCESS
- + ")",
- nativeQuery = true)
- int incrementSeatsUsed(@Param("teamId") Long teamId);
-
@Query(
value =
"SELECT "
diff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustom.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustom.java
new file mode 100644
index 0000000000..460ea9395a
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustom.java
@@ -0,0 +1,24 @@
+package stirling.software.saas.repository;
+
+/**
+ * The atomic seat claim: one conditional UPDATE over {@code saas_team_extensions}, {@code
+ * linked_instance} and {@code procurement_deal}, where 0 rows means capacity is exhausted and no
+ * lock is taken - which a locked read-modify-write in ORM would not preserve. Declares its table so
+ * the commit scopes cache invalidation to {@code saas_team_extensions}.
+ */
+public interface SaasTeamExtensionsRepositoryCustom {
+
+ /**
+ * The claim as a standalone statement, so tests can execute it against a database without
+ * booting Hibernate.
+ */
+ String INCREMENT_SEATS_SQL =
+ "UPDATE stirling_pdf.saas_team_extensions e SET seats_used = seats_used + 1 WHERE"
+ + " team_id = :teamId AND ("
+ + SaasTeamExtensionsRepository.FLEET_SEATS
+ + " < max_seats OR "
+ + SaasTeamExtensionsRepository.ENTERPRISE_ACCESS
+ + ")";
+
+ int incrementSeatsUsed(Long teamId);
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustomImpl.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustomImpl.java
new file mode 100644
index 0000000000..1d19ef7d88
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepositoryCustomImpl.java
@@ -0,0 +1,24 @@
+package stirling.software.saas.repository;
+
+import org.hibernate.query.NativeQuery;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+
+/** See {@link SaasTeamExtensionsRepositoryCustom}. */
+class SaasTeamExtensionsRepositoryCustomImpl implements SaasTeamExtensionsRepositoryCustom {
+
+ @PersistenceContext private EntityManager entityManager;
+
+ @Override
+ public int incrementSeatsUsed(Long teamId) {
+ return entityManager
+ .createNativeQuery(INCREMENT_SEATS_SQL)
+ .setParameter("teamId", teamId)
+ .unwrap(NativeQuery.class)
+ // The claim writes only saas_team_extensions; declaring it keeps the commit from
+ // evicting every cached region. The subqueries are reads.
+ .addSynchronizedQuerySpace("saas_team_extensions")
+ .executeUpdate();
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/cache/SaasSecondLevelCacheTest.java b/app/saas/src/test/java/stirling/software/saas/cache/SaasSecondLevelCacheTest.java
new file mode 100644
index 0000000000..e1e2c93ac1
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/cache/SaasSecondLevelCacheTest.java
@@ -0,0 +1,103 @@
+package stirling.software.saas.cache;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.stat.Statistics;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.boot.persistence.autoconfigure.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import jakarta.persistence.EntityManagerFactory;
+
+import stirling.software.saas.legal.LegalConsent;
+import stirling.software.saas.legal.LegalConsentRepository;
+
+/**
+ * Boots the SaaS entities under the same fail-fast cache strategy production uses. A typo in a SaaS
+ * {@code @Cache} region would otherwise pass the proprietary suite and fail only in a SaaS runtime,
+ * and an uncached SaaS entity would silently skip the second-level cache.
+ */
+@DataJpaTest(
+ properties = {
+ "spring.jpa.properties.hibernate.cache.use_second_level_cache=true",
+ "spring.jpa.properties.hibernate.cache.use_query_cache=false",
+ "spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.internal.JCacheRegionFactory",
+ "spring.jpa.properties.hibernate.javax.cache.provider=com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider",
+ "spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=fail",
+ "spring.jpa.properties.hibernate.generate_statistics=true",
+ "spring.jpa.properties.jakarta.persistence.sharedCache.mode=ENABLE_SELECTIVE"
+ })
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class SaasSecondLevelCacheTest {
+
+ @Autowired private LegalConsentRepository consentRepository;
+
+ @Autowired private EntityManagerFactory entityManagerFactory;
+
+ @Autowired private PlatformTransactionManager transactionManager;
+
+ private Statistics statistics;
+ private TransactionTemplate txTemplate;
+
+ @BeforeEach
+ void setUp() {
+ statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
+ statistics.setStatisticsEnabled(true);
+ txTemplate = new TransactionTemplate(transactionManager);
+ statistics.clear();
+ }
+
+ @Test
+ void saasConsentRegionCachesAcrossTransactions() {
+ AtomicReference<Long> consentIdRef = new AtomicReference<>();
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ LegalConsent consent = new LegalConsent();
+ consent.setTeamId(7L);
+ consent.setUserId(42L);
+ consent.setDocumentId("eula");
+ consent.setDocumentVersion("2026.09");
+ consent.setContext("trial");
+ consentIdRef.set(consentRepository.save(consent).getConsentId());
+ });
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ LegalConsent loaded =
+ consentRepository.findById(consentIdRef.get()).orElseThrow();
+ assertThat(loaded.getDocumentId()).isEqualTo("eula");
+ });
+
+ long hitsBefore = statistics.getSecondLevelCacheHitCount();
+
+ txTemplate.executeWithoutResult(
+ status -> {
+ LegalConsent loaded =
+ consentRepository.findById(consentIdRef.get()).orElseThrow();
+ assertThat(loaded.getDocumentVersion()).isEqualTo("2026.09");
+ });
+
+ assertThat(statistics.getSecondLevelCacheHitCount()).isGreaterThan(hitsBefore);
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ // SaaS entities associate back to proprietary ones (e.g. TeamInvitation.inviteeUser), so
+ // both packages join one persistence unit exactly like the SaaS runtime.
+ @EntityScan(basePackages = {"stirling.software.saas", "stirling.software.proprietary"})
+ @EnableJpaRepositories(basePackages = "stirling.software.saas.legal")
+ static class TestApp {}
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/model/SaasSidecarDeleteTest.java b/app/saas/src/test/java/stirling/software/saas/model/SaasSidecarDeleteTest.java
new file mode 100644
index 0000000000..5b0a587a3f
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/model/SaasSidecarDeleteTest.java
@@ -0,0 +1,144 @@
+package stirling.software.saas.model;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.boot.persistence.autoconfigure.EntityScan;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+
+import stirling.software.proprietary.model.Team;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamRepository;
+import stirling.software.saas.repository.SaasTeamExtensionsRepository;
+import stirling.software.saas.repository.SaasUserExtensionsRepository;
+
+/**
+ * The sidecars are removed by the database's {@code ON DELETE CASCADE}, which Hibernate does not
+ * see as an entity-delete: with a second-level cache a primary-key lookup would serve the deleted
+ * row until the region expired. Pins the lifecycle so re-enabling caching requires delete-path
+ * eviction.
+ */
+@DataJpaTest(
+ properties = {
+ "spring.jpa.properties.hibernate.cache.use_second_level_cache=true",
+ "spring.jpa.properties.hibernate.cache.use_query_cache=false",
+ "spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.internal.JCacheRegionFactory",
+ "spring.jpa.properties.hibernate.javax.cache.provider=com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider",
+ "spring.jpa.properties.jakarta.persistence.sharedCache.mode=ENABLE_SELECTIVE"
+ })
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class SaasSidecarDeleteTest {
+
+ @Autowired private UserRepository userRepository;
+ @Autowired private TeamRepository teamRepository;
+ @Autowired private SaasUserExtensionsRepository userExtensionsRepository;
+ @Autowired private SaasTeamExtensionsRepository teamExtensionsRepository;
+ @Autowired private EntityManagerFactory entityManagerFactory;
+ @Autowired private EntityManager entityManager;
+ @Autowired private PlatformTransactionManager transactionManager;
+
+ private TransactionTemplate tx;
+
+ @BeforeEach
+ void setUp() {
+ tx = new TransactionTemplate(transactionManager);
+ }
+
+ @Test
+ void deletedUserSidecarIsNotReadable() {
+ AtomicLong userId = new AtomicLong();
+ tx.executeWithoutResult(
+ status -> {
+ User user = new User();
+ user.setUsername("cascade-delete-user");
+ user.setPassword("x");
+ user = userRepository.save(user);
+ userId.set(user.getId());
+ userExtensionsRepository.save(new SaasUserExtensions(user));
+ entityManager.flush();
+ });
+
+ tx.executeWithoutResult(
+ status -> userExtensionsRepository.findById(userId.get()).orElseThrow());
+
+ // The real deletion path: UserService.deleteUser ends in userRepository.delete(user).
+ tx.executeWithoutResult(
+ status ->
+ userRepository.delete(userRepository.findById(userId.get()).orElseThrow()));
+
+ tx.executeWithoutResult(
+ status ->
+ assertThat(userExtensionsRepository.findById(userId.get()))
+ .as(
+ "a cascade-deleted sidecar must not be resolved after the parent"
+ + " delete commits")
+ .isEmpty());
+ assertThat(entityManagerFactory.getCache().contains(SaasUserExtensions.class, userId.get()))
+ .isFalse();
+ }
+
+ @Test
+ void deletedTeamSidecarIsNotReadable() {
+ AtomicLong teamId = new AtomicLong();
+ tx.executeWithoutResult(
+ status -> {
+ Team team = new Team();
+ team.setName("cascade-delete-team");
+ team = teamRepository.save(team);
+ teamId.set(team.getId());
+ SaasTeamExtensions extensions = new SaasTeamExtensions();
+ extensions.setTeam(team);
+ teamExtensionsRepository.save(extensions);
+ entityManager.flush();
+ });
+
+ tx.executeWithoutResult(
+ status -> teamExtensionsRepository.findById(teamId.get()).orElseThrow());
+
+ // The real deletion path: TeamController deletes the row through the repository.
+ tx.executeWithoutResult(
+ status ->
+ teamRepository.delete(teamRepository.findById(teamId.get()).orElseThrow()));
+
+ tx.executeWithoutResult(
+ status ->
+ assertThat(teamExtensionsRepository.findById(teamId.get()))
+ .as(
+ "a cascade-deleted sidecar must not be resolved after the parent"
+ + " delete commits")
+ .isEmpty());
+ assertThat(entityManagerFactory.getCache().contains(SaasTeamExtensions.class, teamId.get()))
+ .isFalse();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage
+ @EntityScan(
+ basePackages = {
+ "stirling.software.saas",
+ "stirling.software.proprietary.security.model",
+ "stirling.software.proprietary.model"
+ })
+ @EnableJpaRepositories(
+ basePackages = {
+ "stirling.software.saas",
+ "stirling.software.proprietary.security.database.repository",
+ "stirling.software.proprietary.security.repository"
+ })
+ static class TestApp {}
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java
index bde4480e54..45e3380246 100644
--- a/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java
@@ -65,6 +65,10 @@ class FleetSeatQueriesTest {
.replace(":teamId", "1");
}
+ private static String claimSql() {
+ return SaasTeamExtensionsRepositoryCustom.INCREMENT_SEATS_SQL.replace(":teamId", "1");
+ }
+
private static long total(Connection db) throws Exception {
try (var statement = db.createStatement();
var rows = statement.executeQuery(query("fleetUsersInUse"))) {
@@ -83,7 +87,7 @@ class FleetSeatQueriesTest {
private static int claim(Connection db) throws Exception {
try (var statement = db.createStatement()) {
- return statement.executeUpdate(query("incrementSeatsUsed"));
+ return statement.executeUpdate(claimSql());
}
}
}