diff --git a/grails-cache/build.gradle b/grails-cache/build.gradle index 2f7ca078a88..31af1252de1 100644 --- a/grails-cache/build.gradle +++ b/grails-cache/build.gradle @@ -60,6 +60,7 @@ dependencies { testImplementation project(':grails-testing-support-datamapping') testImplementation project(':grails-testing-support-web') + testImplementation testFixtures(project(':grails-core')) // LogCapture testImplementation 'org.spockframework:spock-core' testCompileOnly 'org.slf4j:slf4j-nop' // Prevents warning about missing slf4j implementation during compilation diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy new file mode 100644 index 00000000000..893213409b3 --- /dev/null +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/MissingCacheReporter.groovy @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.plugin.cache + +import java.util.concurrent.ConcurrentHashMap + +import groovy.transform.CompileStatic +import groovy.util.logging.Slf4j + +import org.springframework.cache.CacheManager + +/** + * Reports a cache the cache manager does not have, for the code the cache annotations generate. + * + *

A cache manager answers null for a name it has no cache of, as {@code JCacheCacheManager} does + * for a cache it was not configured with. The annotated method then runs as it does without a cache + * manager, and this says so once for each cache manager and name.

+ * + * @since 8.0.1 + */ +@Slf4j +@CompileStatic +final class MissingCacheReporter { + + /** The names of the caches reported missing, for each cache manager. */ + private static final Map> REPORTED = Collections.synchronizedMap( + new WeakHashMap>()) + + private MissingCacheReporter() { + } + + /** + * @param cacheManager the cache manager without the cache + * @param cacheName the name the annotation gives + * @param owner the class of the annotated method + */ + static void report(CacheManager cacheManager, String cacheName, Class owner) { + Set reported = REPORTED.computeIfAbsent(cacheManager) { CacheManager ignored -> + ConcurrentHashMap. newKeySet() + } + if (reported.add(cacheName)) { + log.warn('{} does not cache with {}: its cache manager, {}, has no cache of that name, so the methods ' + + 'run uncached. Configure the cache in that cache manager.', owner.name, cacheName, cacheManager.getClass().name) + } + } +} diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy index a4087dcab04..de17f546fd3 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/AbstractCacheTransformation.groovy @@ -51,6 +51,7 @@ import org.grails.datastore.gorm.transform.AbstractMethodDecoratingTransformatio import org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation import org.grails.datastore.mapping.model.config.GormProperties import org.grails.plugin.cache.GrailsCacheManagerAware +import org.grails.plugin.cache.MissingCacheReporter import static org.codehaus.groovy.ast.ClassHelper.CLOSURE_TYPE import static org.codehaus.groovy.ast.ClassHelper.MAP_TYPE @@ -59,15 +60,19 @@ import static org.codehaus.groovy.ast.ClassHelper.STRING_TYPE import static org.codehaus.groovy.ast.ClassHelper.int_TYPE import static org.codehaus.groovy.ast.ClassHelper.make import static org.codehaus.groovy.ast.tools.GeneralUtils.args +import static org.codehaus.groovy.ast.tools.GeneralUtils.block import static org.codehaus.groovy.ast.tools.GeneralUtils.callX import static org.codehaus.groovy.ast.tools.GeneralUtils.classX import static org.codehaus.groovy.ast.tools.GeneralUtils.constX import static org.codehaus.groovy.ast.tools.GeneralUtils.declS +import static org.codehaus.groovy.ast.tools.GeneralUtils.ifElseS import static org.codehaus.groovy.ast.tools.GeneralUtils.ifS +import static org.codehaus.groovy.ast.tools.GeneralUtils.notNullX import static org.codehaus.groovy.ast.tools.GeneralUtils.notX import static org.codehaus.groovy.ast.tools.GeneralUtils.param import static org.codehaus.groovy.ast.tools.GeneralUtils.params import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS +import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt import static org.codehaus.groovy.ast.tools.GeneralUtils.varX import static org.grails.datastore.gorm.transform.AstMethodDispatchUtils.callD @@ -102,6 +107,10 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans param(MAP_TYPE, 'methodParams'))) private static final ClassNode CACHE_MANAGER_CLASS_NODE = make(CacheManager) private static final MethodNode GET_CACHE_METHOD_NODE = CACHE_MANAGER_CLASS_NODE.getMethod('getCache', [new Parameter(STRING_TYPE, 'name')] as Parameter[]) + private static final ClassNode MISSING_CACHE_REPORTER_CLASS_NODE = make(MissingCacheReporter) + private static final MethodNode REPORT_MISSING_CACHE_METHOD_NODE = MISSING_CACHE_REPORTER_CLASS_NODE.getMethod('report', + [new Parameter(CACHE_MANAGER_CLASS_NODE, 'cacheManager'), new Parameter(STRING_TYPE, 'cacheName'), + new Parameter(make(Class), 'owner')] as Parameter[]) private static final MethodNode MAP_PUT_METHOD = MAP_TYPE.getMethod('put', [new Parameter(OBJECT_TYPE, 'key'), new Parameter(OBJECT_TYPE, 'value')] as Parameter[]) public static final String CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME = '$_cache_originalMethodReturnValue' @@ -171,6 +180,29 @@ abstract class AbstractCacheTransformation extends AbstractMethodDecoratingTrans return cacheVariableExpression } + /** + * Adds to the caching block what runs only where the cache manager has the cache the annotation + * names, and returns the block to add it to. A cache manager answers null for a name it has no + * cache of, as {@code JCacheCacheManager} does for a cache it was not configured with, and the + * method then runs as it does without a cache manager, which is reported once. + * + * @param annotationNode the cache annotation, whose {@code value} names the cache + * @param classNode the class the method is in, which the report names + * @param cacheVariableExpression the cache declared by {@link #declareCache} + * @param cacheBlock the caching block + * @return the block that runs where there is a cache + */ + protected BlockStatement whereCacheExists(AnnotationNode annotationNode, ClassNode classNode, + VariableExpression cacheVariableExpression, BlockStatement cacheBlock) { + BlockStatement whereCacheExists = block() + Object cacheName = ((ConstantExpression) annotationNode.getMember('value')).value + MethodCallExpression report = callX(classX(MISSING_CACHE_REPORTER_CLASS_NODE), 'report', + args(varX(GRAILS_CACHE_MANAGER_PROPERTY_NAME), constX(cacheName), classX(classNode.plainNodeReference))) + report.methodTarget = REPORT_MISSING_CACHE_METHOD_NODE + cacheBlock.addStatement(ifElseS(notNullX(cacheVariableExpression), whereCacheExists, stmt(report))) + return whereCacheExists + } + protected VariableExpression declareCacheKey(SourceUnit sourceUnit, AnnotationNode annotationNode, ClassNode classNode, MethodNode methodNode, BlockStatement cacheBlock) { ArgumentListExpression createKeyArgs = args( constX(classNode.getName()), diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy index 8dd0d6fa427..921e8b07f79 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheEvictTransformation.groovy @@ -67,6 +67,9 @@ class CacheEvictTransformation extends AbstractCacheTransformation { // Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("..."); VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock) + // if($_cache_cacheVariable != null) { ... } else { report the missing cache } + BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock) + Statement statement boolean clearAllEntries = false @@ -82,16 +85,16 @@ class CacheEvictTransformation extends AbstractCacheTransformation { statement = stmt(callX(cacheDeclaration, 'clear')) } else { // def $_method_parameter_map = [name:value] - declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock) + declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock) // def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map) - VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock) + VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock) // $_cache_cacheVariable.evict($_cache_cacheKey) statement = stmt(callX(cacheDeclaration, 'evict', cacheKeyDeclaration)) } - cachingBlock.addStatement(statement) + cacheBlock.addStatement(statement) newMethodBody.addStatement( // if(grailsCacheManager != null) diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy index 1cfaa52b5f0..4fafeee996e 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CachePutTransformation.groovy @@ -65,14 +65,17 @@ class CachePutTransformation extends AbstractCacheTransformation { // Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("..."); VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock) + // if($_cache_cacheVariable != null) { ... } else { report the missing cache } + BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock) + // def $_method_parameter_map = [name:value] - declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock) + declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock) // def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map) - VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock) + VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock) VariableExpression originalValueExpr = varX(CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME) - cachingBlock.addStatement( + cacheBlock.addStatement( block( declS(originalValueExpr, originalMethodCallExpr), stmt(callD(cacheDeclaration, 'put', args(cacheKeyDeclaration, originalValueExpr))), diff --git a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy index 2e1ef8ca04f..6dfa54d97f5 100644 --- a/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy +++ b/grails-cache/src/ast/groovy/org/grails/plugin/cache/compiler/CacheableTransformation.groovy @@ -86,15 +86,18 @@ class CacheableTransformation extends AbstractCacheTransformation { // Cache $_cache_cacheVariable = this.grailsCacheManager.getCache("..."); VariableExpression cacheDeclaration = declareCache(annotationNode, cacheManagerVariableExpression, cachingBlock) + // if($_cache_cacheVariable != null) { ... } else { report the missing cache } + BlockStatement cacheBlock = whereCacheExists(annotationNode, classNode, cacheDeclaration, cachingBlock) + // def $_method_parameter_map = [name:value] - declareAndInitializeParameterValueMap(annotationNode, methodNode, cachingBlock) + declareAndInitializeParameterValueMap(annotationNode, methodNode, cacheBlock) // def $_cache_cacheKey = customCacheKeyGenerator.generate(className, methodName, hashCode, $_method_parameter_map) - VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cachingBlock) + VariableExpression cacheKeyDeclaration = declareCacheKey(sourceUnit, annotationNode, classNode, methodNode , cacheBlock) // ValueWrapper $_cache_valueWrapper = $_cache_cacheVariable.get($_cache_cacheKey); VariableExpression cacheValueWrapper = varX(CACHE_VALUE_WRAPPER_LOCAL_VARIABLE_NAME, make(Cache.ValueWrapper)) - cachingBlock.addStatement( + cacheBlock.addStatement( declS(cacheValueWrapper, callD(cacheDeclaration, 'get', cacheKeyDeclaration)) ) @@ -106,7 +109,7 @@ class CacheableTransformation extends AbstractCacheTransformation { // return $_cache_originalMethodReturnValue; // } VariableExpression originalValueExpr = varX(CACHE_ORIGINAL_METHOD_RETURN_VALUE_LOCAL_VARIABLE_NAME) - cachingBlock.addStatement( + cacheBlock.addStatement( ifElseS(notNullX(cacheValueWrapper), returnS(callD(cacheValueWrapper, 'get')), block( diff --git a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy index 95ad1363bc3..d6d859e485e 100644 --- a/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy +++ b/grails-cache/src/main/groovy/grails/plugin/cache/CacheGrailsPlugin.groovy @@ -28,6 +28,7 @@ import org.springframework.cache.Cache import grails.plugins.Plugin import org.grails.plugin.cache.GrailsCacheManager +import org.grails.plugin.cache.GrailsCacheManagerFallback /** * Configures the cache plugin. @@ -80,6 +81,10 @@ class CacheGrailsPlugin extends Plugin { bean(CustomCacheKeyGenerator).conditionalOnMissingBeanName() + // Spring takes grailsCacheManager for the field of a cache-aware class beside a second cache + // manager, such as the one cacheUsers defines, where it cannot otherwise choose. + bean(GrailsCacheManagerFallback).staticMethod() + bean(GrailsCacheManager).conditionalOnMissingBeanName() { CachePluginConfiguration grailsCacheConfiguration -> if (cacheManagerType == 'GrailsConcurrentLinkedMapCacheManager') { return new GrailsConcurrentLinkedMapCacheManager(configuration: grailsCacheConfiguration) diff --git a/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy new file mode 100644 index 00000000000..eab8bdfe92d --- /dev/null +++ b/grails-cache/src/main/groovy/org/grails/plugin/cache/GrailsCacheManagerFallback.groovy @@ -0,0 +1,294 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.plugin.cache + +import java.lang.ref.Reference +import java.lang.ref.ReferenceQueue +import java.lang.ref.WeakReference +import java.util.concurrent.ConcurrentHashMap + +import groovy.transform.CompileStatic + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.BeanFactory +import org.springframework.beans.factory.BeanFactoryAware +import org.springframework.beans.factory.config.BeanDefinitionHolder +import org.springframework.beans.factory.config.BeanFactoryPostProcessor +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory +import org.springframework.beans.factory.config.DependencyDescriptor +import org.springframework.beans.factory.support.AutowireCandidateResolver +import org.springframework.beans.factory.support.DefaultListableBeanFactory +import org.springframework.cache.CacheManager +import org.springframework.core.ResolvableType + +/** + * Gives a cache-aware class the cache manager named {@code grailsCacheManager} where Spring cannot choose + * the cache manager it injects, and leaves Spring's choice as it is everywhere else. + * + *

{@link GrailsCacheManagerAware} injects a {@code CacheManager} by type. Beside a second cache + * manager, such as the one the Spring Security plugin defines when {@code cacheUsers} is set, Spring + * cannot choose by type, and falls back to the bean named like the field. A trait's field is renamed in + * the class that implements it, so no bean matched, and the application failed to start.

+ * + *

This wraps the bean factory's autowire candidate resolver. Spring asks the resolver, before it + * resolves a dependency, for a proxy to inject in its place; for the trait's field the resolver answers + * with the field's resolution itself. It is Spring's own, for the bean being injected, with one change: + * where Spring would fail because it cannot choose, and {@code grailsCacheManager} is one of the cache + * managers it cannot choose between, it takes {@code grailsCacheManager}, unless that resolves to null. + * Everywhere else Spring chooses as it did: the only cache manager, the one marked primary or the one + * with the highest priority, judged at that moment, leaving out the bean being injected. Any other + * injection of a cache manager is left alone.

+ * + *

As Spring's own resolution of the field would, the resolver registers the bean as depending on the + * cache manager it took, and remembers that cache manager for the injection point Spring resolved, + * which Spring passes again for the next injection of the bean, as for a prototype's next instance. + * Spring's field injection remembers its own choice the same way, until the bean's definition is reset; + * then it resolves the field with a new injection point, which this resolver has not seen. The + * injection that Spring AOT generates passes a new one every time, and so resolves every time, as it + * did. Where the cache manager remembered fails, the field is resolved again, as Spring resolves it + * again.

+ * + * @since 8.0.1 + */ +@CompileStatic +class GrailsCacheManagerFallback implements BeanFactoryPostProcessor { + + static final String CACHE_MANAGER_BEAN_NAME = 'grailsCacheManager' + + /** The name the trait's field has in each class that implements it. */ + static final String FIELD_NAME = "${GrailsCacheManagerAware.name.replace('.', '_')}__${CACHE_MANAGER_BEAN_NAME}".toString() + + @Override + void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + if (beanFactory instanceof DefaultListableBeanFactory) { + DefaultListableBeanFactory listable = (DefaultListableBeanFactory) beanFactory + if (!(listable.autowireCandidateResolver instanceof CandidateResolver)) { + listable.autowireCandidateResolver = new CandidateResolver(listable.autowireCandidateResolver) + } + } + } + + /** Whether the dependency is the trait's cache manager field. */ + static boolean isTraitField(DependencyDescriptor descriptor) { + descriptor.field != null && descriptor.field.name == FIELD_NAME && descriptor.field.type == CacheManager && + GrailsCacheManagerAware.isAssignableFrom(descriptor.field.declaringClass) + } + + /** + * The bean factory's resolver, resolving the trait's field with the fall back to + * {@code grailsCacheManager}. + */ + @CompileStatic + static class CandidateResolver implements AutowireCandidateResolver, BeanFactoryAware { + + private final AutowireCandidateResolver delegate + + private DefaultListableBeanFactory beanFactory + + /** + * The name of the cache manager taken for each injection point Spring resolved, where Spring would + * remember it: one bean, of the field's type. Held as long as Spring holds the injection point. + */ + private final Map remembered = new ConcurrentHashMap() + + private final ReferenceQueue forgotten = new ReferenceQueue() + + CandidateResolver(AutowireCandidateResolver delegate) { + this.delegate = delegate + } + + @Override + void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory instanceof DefaultListableBeanFactory ? (DefaultListableBeanFactory) beanFactory : null + if (delegate instanceof BeanFactoryAware) { + ((BeanFactoryAware) delegate).beanFactory = beanFactory + } + } + + @Override + Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) { + Object proxy = delegate.getLazyResolutionProxyIfNecessary(descriptor, beanName) + if (proxy != null || beanFactory == null || descriptor instanceof FallbackDescriptor || + descriptor instanceof RememberedDescriptor || !isTraitField(descriptor)) { + return proxy + } + Object shortcut = descriptor.resolveShortcut(beanFactory) + if (shortcut != null) { + // as the first step of Spring's resolution, for an injection point resolved in advance + return shortcut + } + forgetCollected() + InjectionPointKey injectionPoint = new InjectionPointKey(descriptor, null) + String rememberedName = remembered.get(injectionPoint) + if (rememberedName != null) { + try { + return beanFactory.doResolveDependency(new RememberedDescriptor(descriptor, rememberedName), beanName, null, null) + } + catch (BeansException ignored) { + // as the injection, which resolves the field again where the bean it remembers fails + remembered.remove(injectionPoint, rememberedName) + } + } + FallbackDescriptor fallback = new FallbackDescriptor(descriptor, beanFactory) + Set autowiredBeanNames = new LinkedHashSet() + Object value = beanFactory.doResolveDependency(fallback, beanName, autowiredBeanNames, null) + if (fallback.fellBack) { + autowiredBeanNames << CACHE_MANAGER_BEAN_NAME + } + if (beanName != null && (value != null || descriptor.required)) { + // as the injection registers the bean it injects, which this answer takes the place of + for (String autowiredBeanName : autowiredBeanNames) { + if (beanFactory.containsBean(autowiredBeanName)) { + beanFactory.registerDependentBean(autowiredBeanName, beanName) + } + } + } + if (value != null && autowiredBeanNames.size() == 1) { + String autowiredBeanName = autowiredBeanNames.iterator().next() + if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, descriptor.dependencyType)) { + remembered.put(new InjectionPointKey(descriptor, forgotten), autowiredBeanName) + } + } + return value + } + + /** Drops what was remembered for injection points Spring no longer holds. */ + private void forgetCollected() { + Reference reference + while ((reference = forgotten.poll()) != null) { + remembered.remove(reference) + } + } + + @Override + boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { + delegate.isAutowireCandidate(bdHolder, descriptor) + } + + @Override + boolean isRequired(DependencyDescriptor descriptor) { + delegate.isRequired(descriptor) + } + + @Override + boolean hasQualifier(DependencyDescriptor descriptor) { + delegate.hasQualifier(descriptor) + } + + @Override + String getSuggestedName(DependencyDescriptor descriptor) { + delegate.getSuggestedName(descriptor) + } + + @Override + Object getSuggestedValue(DependencyDescriptor descriptor) { + delegate.getSuggestedValue(descriptor) + } + + @Override + Class getLazyResolutionProxyClass(DependencyDescriptor descriptor, String beanName) { + delegate.getLazyResolutionProxyClass(descriptor, beanName) + } + + @Override + AutowireCandidateResolver cloneIfNecessary() { + new CandidateResolver(delegate.cloneIfNecessary()) + } + } + + /** + * The identity of an injection point Spring passed, held weakly, so that an injection point is + * remembered as long as Spring holds it, and one equal to it is not taken for it. + */ + @CompileStatic + private static final class InjectionPointKey extends WeakReference { + + private final int hash + + InjectionPointKey(DependencyDescriptor injectionPoint, ReferenceQueue queue) { + super(injectionPoint, queue) + this.hash = System.identityHashCode(injectionPoint) + } + + @Override + int hashCode() { + hash + } + + @Override + boolean equals(Object other) { + if (this.is(other)) { + return true + } + if (!(other instanceof InjectionPointKey)) { + return false + } + Object injectionPoint = get() + injectionPoint != null && injectionPoint.is(((InjectionPointKey) other).get()) + } + } + + /** The trait's field, resolved to the cache manager remembered for it, as Spring resolves a shortcut. */ + @CompileStatic + private static class RememberedDescriptor extends DependencyDescriptor { + + private final String beanName + + RememberedDescriptor(DependencyDescriptor original, String beanName) { + super(original) + this.beanName = beanName + } + + @Override + Object resolveShortcut(BeanFactory beanFactory) throws BeansException { + beanFactory.getBean(beanName, dependencyType) + } + } + + /** The trait's field, falling back to {@code grailsCacheManager} where Spring cannot choose. */ + @CompileStatic + private static class FallbackDescriptor extends DependencyDescriptor { + + private final BeanFactory beanFactory + + boolean fellBack + + FallbackDescriptor(DependencyDescriptor original, BeanFactory beanFactory) { + super(original) + this.beanFactory = beanFactory + } + + @Override + Object resolveNotUnique(ResolvableType type, Map matchingBeans) throws BeansException { + if (!matchingBeans.containsKey(CACHE_MANAGER_BEAN_NAME)) { + return super.resolveNotUnique(type, matchingBeans) + } + Object candidate = matchingBeans.get(CACHE_MANAGER_BEAN_NAME) + // created here if it is not yet, as Spring creates the candidate it chooses + Object grailsCacheManager = candidate instanceof Class ? + resolveCandidate(CACHE_MANAGER_BEAN_NAME, CacheManager, beanFactory) : candidate + // Spring's null bean, which equals null: no cache manager to fall back to + if (grailsCacheManager == null || grailsCacheManager.equals(null)) { + return super.resolveNotUnique(type, matchingBeans) + } + fellBack = true + grailsCacheManager + } + } +} diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy index 95900ebe6fc..cfd08c85f95 100644 --- a/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy +++ b/grails-cache/src/test/groovy/grails/plugin/cache/CacheAutoConfigurationSpec.groovy @@ -18,8 +18,18 @@ */ package grails.plugin.cache +import java.util.function.Supplier + import groovy.transform.CompileStatic +import jakarta.annotation.Priority + +import org.springframework.beans.factory.FactoryBean +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.SmartLifecycle import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.env.MapPropertySource @@ -27,6 +37,7 @@ import grails.core.DefaultGrailsApplication import grails.core.GrailsApplication import org.grails.plugin.cache.GrailsCacheManager +import org.grails.plugin.cache.GrailsCacheManagerAware import spock.lang.Specification import spock.lang.Unroll @@ -144,6 +155,271 @@ class CacheAutoConfigurationSpec extends Specification { context.close() } + void 'a grailsCacheManager the application defines is used beside another cache manager'() { + given: 'a cache manager of the application\'s own as grailsCacheManager, and Spring Security\'s beside it' + GrailsCacheManager mine = Mock(GrailsCacheManager) + AnnotationConfigApplicationContext context = buildContext([:], mine, [cacheManager: new ConcurrentMapCacheManager()]) + + expect: 'where Spring cannot choose, the cache-aware beans get it, so the context starts and caches with it' + context.getBean(CacheAware).grailsCacheManager.is(mine) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(mine) + + cleanup: + context.close() + } + + @Unroll + void 'a grailsCacheManager built from a cache-aware bean starts beside a cache manager #preferred, which that bean gets, as in 8.0.0'() { + given: 'the application\'s grailsCacheManager, created from a bean that has a cache manager injected itself' + GrailsCacheManager mine = Mock(GrailsCacheManager) + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + + and: 'the cache manager Spring prefers, created first' + if (preferred == 'with a priority') { + context.registerBean('preferredCacheManager', HighPriorityCacheManager) + } + else if (preferred == 'with a priority only on the object its factory returns') { + context.registerBean('preferredCacheManager', CacheManager, { -> new HighPriorityCacheManager() } as Supplier) + } + else if (preferred == 'that a factory bean naming only CacheManager makes, with a priority') { + context.registerBean('preferredCacheManager', PriorityProductFactoryBean) + } + else if (preferred == 'with a priority, which the key generator creates as the cache-aware bean is injected') { + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + context.registerBean('preferredCacheManager', CacheManager, + { -> new HighPriorityCacheManager() } as Supplier, lazy) + context.registerBean('customCacheKeyGenerator', GrailsCacheKeyGenerator, { -> + context.getBean('preferredCacheManager') + new CustomCacheKeyGenerator() + } as Supplier, lazy) + } + else { + context.registerBean('preferredCacheManager', ConcurrentMapCacheManager, + { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) + } + context.registerBean('grailsCacheManager', GrailsCacheManager, { -> + context.getBean(CacheAware) + mine + } as Supplier) + context.registerBean(CacheAware) + context.register(CacheAutoConfiguration) + + when: + context.refresh() + + then: 'the context starts, and the cache-aware beans get the cache manager Spring prefers' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('preferredCacheManager')) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('preferredCacheManager')) + + cleanup: + context.close() + + where: + preferred << ['with a priority', 'with a priority only on the object its factory returns', + 'that a factory bean naming only CacheManager makes, with a priority', + 'with a priority, which the key generator creates as the cache-aware bean is injected', 'marked primary'] + } + + @Unroll + void 'a grailsCacheManager that is cache-aware itself gets the other cache manager, as in 8.0.0, with circular references #circular'() { + given: 'Spring leaves a bean out of the candidates for its own fields' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.allowCircularReferences = circular == 'allowed' + context.registerBean('grailsCacheManager', CacheAwareGrailsCacheManager) + CacheManager other = new ConcurrentMapCacheManager() + context.registerBean('other', CacheManager, { -> other } as Supplier) + context.registerBean(CacheAware) + context.register(CacheAutoConfiguration) + + when: + context.refresh() + + then: 'it starts, and grailsCacheManager is not given itself' + context.getBean('grailsCacheManager', GrailsCacheManagerAware).grailsCacheManager.is(other) + + and: 'a cache-aware bean beside both, where Spring cannot choose, gets grailsCacheManager' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + + where: + circular << ['allowed', 'not allowed'] + } + + void 'a cache-aware bean given grailsCacheManager depends on it, so it stops while that cache manager still runs'() { + given: 'a grailsCacheManager stopped in a later phase than the cache-aware bean, and another cache manager' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.registerBean('grailsCacheManager', LifecycleGrailsCacheManager) + context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + context.registerBean('service', LifecycleService) + context.register(CacheAutoConfiguration) + context.refresh() + LifecycleService service = context.getBean('service', LifecycleService) + + expect: 'it is given grailsCacheManager, and registered as depending on it, as an injection registers it' + service.grailsCacheManager.is(context.getBean('grailsCacheManager')) + 'service' in context.beanFactory.getDependentBeans('grailsCacheManager') + + when: + context.close() + + then: 'it stops first, while grailsCacheManager still runs' + service.stoppedWhileCacheManagerRan + } + + void 'another cache manager in the context, such as the one Spring Security caches users with, is not taken for the Grails one'() { + given: 'Spring Security defines cacheManager when cacheUsers is set' + CacheManager other = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: other]) + + expect: 'the context starts, and what the plugin caches with is its own cache manager' + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + } + + void 'with caching disabled, the one cache manager the context has is used, as before'() { + given: + CacheManager only = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, [cacheManager: only]) + + expect: + context.getBean(CacheAware).grailsCacheManager.is(only) + + cleanup: + context.close() + } + + void 'with caching disabled and several cache managers, the one marked primary is used, as Spring chose it before'() { + given: + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, + [cacheManager: new ConcurrentMapCacheManager(), primaryCacheManager: primary], 'primaryCacheManager') + + expect: + context.getBean(CacheAware).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + + void 'a cache manager marked primary beside the Grails one is still used, as in 8.0.0'() { + given: 'an application\'s own cache manager, marked primary' + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext([:], null, [cacheManager: primary], 'cacheManager') + + expect: 'Spring chooses as it did; the name is only taken where it cannot' + context.getBean(CacheAware).grailsCacheManager.is(primary) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + + void 'a lazy cache manager is not created to find the Grails one'() { + given: 'a lazy cache manager whose store is down, beside the plugin\'s' + AnnotationConfigApplicationContext context = buildContext([:], null, [:], null, [unreachableCacheManager: STORE_DOWN]) + + expect: 'the context starts, and the Grails cache manager is used' + context.getBean(CacheAware).grailsCacheManager.is(context.getBean('grailsCacheManager')) + context.getBean(GrailsCacheAdminService).grailsCacheManager.is(context.getBean('grailsCacheManager')) + + cleanup: + context.close() + } + + void 'a lazy cache manager is not created to find the primary one where there is no Grails one'() { + given: + CacheManager primary = new ConcurrentMapCacheManager() + AnnotationConfigApplicationContext context = buildContext(['grails.cache.enabled': 'false'], null, + [primaryCacheManager: primary], 'primaryCacheManager', [unreachableCacheManager: STORE_DOWN]) + + expect: + context.getBean(CacheAware).grailsCacheManager.is(primary) + + cleanup: + context.close() + } + + private static final Supplier STORE_DOWN = { -> + throw new IllegalStateException('the cache store is down') + } as Supplier + + /** A cache manager Spring prefers over others by the priority of its class. */ + @Priority(1) + static class HighPriorityCacheManager extends ConcurrentMapCacheManager { + } + + /** A factory bean that names only CacheManager as its type, and makes a cache manager with a priority. */ + static class PriorityProductFactoryBean implements FactoryBean { + + @Override + CacheManager getObject() { + new HighPriorityCacheManager() + } + + @Override + Class getObjectType() { + CacheManager + } + } + + /** A grailsCacheManager that is cache-aware itself. */ + static class CacheAwareGrailsCacheManager extends GrailsConcurrentMapCacheManager implements GrailsCacheManagerAware { + } + + /** A grailsCacheManager with a lifecycle, stopped in a later phase than {@link LifecycleService}. */ + static class LifecycleGrailsCacheManager extends GrailsConcurrentMapCacheManager implements SmartLifecycle { + + boolean running + + @Override + void start() { + running = true + } + + @Override + void stop() { + running = false + } + + @Override + int getPhase() { + 100 + } + } + + /** A cache-aware bean with a lifecycle, which records whether its cache manager ran when it stopped. */ + static class LifecycleService implements GrailsCacheManagerAware, SmartLifecycle { + + boolean running + + boolean stoppedWhileCacheManagerRan + + @Override + void start() { + running = true + } + + @Override + void stop() { + stoppedWhileCacheManagerRan = ((LifecycleGrailsCacheManager) grailsCacheManager).running + running = false + } + + @Override + int getPhase() { + 0 + } + } + + /** A class the cache transformations make cache-aware, as they do a service with a cached method. */ + static class CacheAware implements GrailsCacheManagerAware { + } + /** * A plugin wired the way the runtime wires it: with the application context and with a * GrailsApplication carrying the same configuration. Both matter - reading the property back out @@ -160,12 +436,25 @@ class CacheAutoConfigurationSpec extends Specification { @CompileStatic private static AnnotationConfigApplicationContext buildContext( - Map properties, GrailsCacheManager userCacheManager = null) { + Map properties, GrailsCacheManager userCacheManager = null, + Map otherCacheManagers = [:], String primary = null, + Map> lazyCacheManagers = [:]) { def context = new AnnotationConfigApplicationContext() context.environment.propertySources.addFirst(new MapPropertySource('test', properties)) if (userCacheManager != null) { context.registerBean('grailsCacheManager', GrailsCacheManager, () -> userCacheManager) } + otherCacheManagers.each { String name, CacheManager cacheManager -> + context.registerBean(name, CacheManager, () -> cacheManager) { BeanDefinition definition -> + definition.primary = name == primary + } + } + lazyCacheManagers.each { String name, Supplier cacheManager -> + context.registerBean(name, CacheManager, cacheManager) { BeanDefinition definition -> + definition.lazyInit = true + } + } + context.registerBean(CacheAware) context.register(CacheAutoConfiguration) context.refresh() return context diff --git a/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy new file mode 100644 index 00000000000..3b5c8944c66 --- /dev/null +++ b/grails-cache/src/test/groovy/grails/plugin/cache/MissingCacheSpec.groovy @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.plugin.cache + +import java.util.function.Supplier + +import ch.qos.logback.classic.Level +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.support.GenericApplicationContext +import spock.lang.Specification +import spock.lang.Unroll + +import org.apache.grails.core.testing.support.LogCapture +import org.grails.plugin.cache.GrailsCacheManagerFallback +import org.grails.plugin.cache.MissingCacheReporter + +/** + * A cache manager answers null for a cache name it has no cache of, as {@code JCacheCacheManager} + * does for a cache it was not configured with. The annotated methods then run uncached, rather than + * failing on the missing cache, and that is reported once for each cache manager and name. + */ +class MissingCacheSpec extends Specification { + + @Unroll + void 'a method whose cache the cache manager does not have runs uncached, compiled #mode'() { + given: 'the annotated class created as a bean, beside a second cache manager, with grailsCacheManager having only the cache named configured' + CacheManager cacheManager = new ConcurrentMapCacheManager('configured') + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) + context.registerBean('grailsCacheManager', CacheManager, { -> cacheManager } as Supplier) + context.registerBean('cacheManager', CacheManager, { -> new ConcurrentMapCacheManager() } as Supplier) + context.registerBean('service', (Class) compile(mode)) + context.refresh() + def service = context.getBean('service') + LogCapture log = new LogCapture(MissingCacheReporter, Level.WARN) + + expect: 'it is injected with grailsCacheManager' + service.grailsCacheManager.is(cacheManager) + + when: 'every annotation is used twice with a cache that is missing' + List results = [service.cached(1), service.cached(1), service.cachedByKey(1), service.cachedByKey(1), + service.put(1), service.put(1)] + service.evict(1) + service.evict(1) + service.evictAll() + service.evictAll() + + then: 'each method ran every time, and answered as it does uncached' + results == [2, 2, 2, 2, 2, 2] + service.calls == 10 + + and: 'each missing cache is reported once' + log.events*.formattedMessage == [ + "CachedService does not cache with missing: its cache manager, ${ConcurrentMapCacheManager.name}, " + + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager.', + "CachedService does not cache with gone: its cache manager, ${ConcurrentMapCacheManager.name}, " + + 'has no cache of that name, so the methods run uncached. Configure the cache in that cache manager.', + ] as List + + when: 'caches the cache manager does have, with the default key and with a key closure' + service.calls = 0 + List cached = [service.cachedWhereConfigured(1), service.cachedWhereConfigured(1), + service.cachedByKeyWhereConfigured(1), service.cachedByKeyWhereConfigured(1)] + + then: 'still cache' + cached == [3, 3, 4, 4] + service.calls == 2 + + cleanup: + log?.close() + context?.close() + + where: + mode << ['statically', 'dynamically'] + } + + private static Class compile(String mode) { + new GroovyShell().evaluate(""" +import grails.plugin.cache.* +import groovy.transform.CompileStatic + +${mode == 'statically' ? '@CompileStatic' : ''} +class CachedService { + int calls + + @Cacheable('missing') + int cached(int x) { calls++; x * 2 } + + @Cacheable(value = 'missing', key = { x }) + int cachedByKey(int x) { calls++; x * 2 } + + @Cacheable('configured') + int cachedWhereConfigured(int x) { calls++; x * 3 } + + @Cacheable(value = 'configured', key = { x + 100 }) + int cachedByKeyWhereConfigured(int x) { calls++; x * 4 } + + @CachePut('missing') + int put(int x) { calls++; x * 2 } + + @CacheEvict('gone') + void evict(int x) { calls++ } + + @CacheEvict(value = 'gone', allEntries = true) + void evictAll() { calls++ } +} +return CachedService +""") as Class + } +} diff --git a/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy new file mode 100644 index 00000000000..84641f659a7 --- /dev/null +++ b/grails-cache/src/test/groovy/org/grails/plugin/cache/GrailsCacheManagerFallbackMatrixSpec.groovy @@ -0,0 +1,584 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.plugin.cache + +import java.util.function.Supplier + +import jakarta.annotation.Priority + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.FactoryBean +import org.springframework.beans.factory.InjectionPoint +import org.springframework.beans.factory.NoUniqueBeanDefinitionException +import org.springframework.beans.factory.UnsatisfiedDependencyException +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor +import org.springframework.beans.factory.aot.AutowiredFieldValueResolver +import org.springframework.beans.factory.config.BeanDefinition +import org.springframework.beans.factory.config.BeanDefinitionCustomizer +import org.springframework.beans.factory.config.DependencyDescriptor +import org.springframework.beans.factory.support.AbstractBeanDefinition +import org.springframework.beans.factory.support.AutowireCandidateResolver +import org.springframework.beans.factory.support.DefaultListableBeanFactory +import org.springframework.beans.factory.support.RegisteredBean +import org.springframework.beans.factory.support.RootBeanDefinition +import org.springframework.cache.CacheManager +import org.springframework.cache.concurrent.ConcurrentMapCacheManager +import org.springframework.context.annotation.AnnotationConfigApplicationContext +import org.springframework.context.annotation.AnnotationConfigUtils +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Scope +import org.springframework.context.support.GenericApplicationContext +import spock.lang.Specification + +import grails.plugin.cache.CustomCacheKeyGenerator +import grails.plugin.cache.GrailsCacheKeyGenerator + +/** + * Which cache manager a cache-aware class is injected with, with the fallback to {@code grailsCacheManager}, + * against the oracle of 8.0.0: the same class, in the same context, without it. + * + *

The matrix crosses the ways a bean named {@code grailsCacheManager} can be defined with none, one + * or two other cache managers, each defined in one of the ways a bean is chosen or passed over for + * injection. One way to define {@code grailsCacheManager} creates it from the cache-aware bean, which so + * has a cache manager injected while {@code grailsCacheManager} is being created, and another makes it + * cache-aware itself, which Spring leaves out of its own candidates. Of the other cache + * managers, some have a priority Spring sees only on their object: one declared as a plain + * {@code CacheManager}, the product of a factory bean that names only {@code CacheManager} as its type, + * and one the cache-aware bean's key generator creates while that bean is injected; another is a factory + * bean that makes a new cache manager each time it is asked. The one deliberate + * difference: where Spring could not choose, which failed startup, the class gets + * {@code grailsCacheManager}, unless another cache manager is preferred, as primary or by priority, where + * Spring rejects the tie itself. Otherwise the choice, and every failure, is 8.0.0's: what the cache-aware + * bean, three instances of a prototype cache-aware bean and a cache-aware {@code grailsCacheManager} get, + * the beans the cache-aware bean is registered as depending on, and how many of each cache manager are + * created, other than {@code grailsCacheManager}.

+ */ +class GrailsCacheManagerFallbackMatrixSpec extends Specification { + + private static final String NAMED = GrailsCacheManagerFallback.CACHE_MANAGER_BEAN_NAME + + private static final List NAMED_KINDS = ['absent', 'plain', 'primary', 'lazy', 'notCandidate', 'wrongType', 'cyclic', + 'cacheAware', 'fallback', 'notDefault', 'priority', 'nullBean'] + + private static final List OTHER_KINDS = ['plain', 'primary', 'lazy', 'notCandidate', 'fallback', 'notDefault', + 'priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator', 'prototypeFactoryBean'] + + private static final List PREFERRED_KINDS = ['primary', 'priority', 'priorityOnObject', 'factoryBean', + 'createdByKeyGenerator'] + + void 'the fallback applies to the field the trait has in a class that implements it'() { + expect: + CacheAware.declaredFields*.name.contains(GrailsCacheManagerFallback.FIELD_NAME) + GrailsCacheManagerFallback.isTraitField(new DependencyDescriptor( + CacheAware.getDeclaredField(GrailsCacheManagerFallback.FIELD_NAME), false)) + !GrailsCacheManagerFallback.isTraitField(new DependencyDescriptor(OwnInjection.getDeclaredField('someCacheManager'), false)) + } + + void 'the cache manager a cache-aware class gets is 8.0.0\'s, except where it failed with none preferred'() { + given: + List> rows = arrangements() + assert rows.size() == NAMED_KINDS.size() * (1 + OTHER_KINDS.size() + OTHER_KINDS.size() * OTHER_KINDS.size()) + + expect: 'every arrangement, each in a context of its own, with the fallback and without it' + List mismatches = [] + rows.each { Map row -> + Map was = run(row, false) + Map now = run(row, true) + boolean namedUsable = row[NAMED] in ['plain', 'primary', 'lazy', 'cacheAware', 'fallback', 'priority'] + boolean anotherPreferred = row.any { String name, String kind -> name != NAMED && kind in PREFERRED_KINDS } + // a context that does not start has failed before the cache-aware bean, where it cannot fall back + boolean fallsBack = was.failed && !was.failedAtStartup && namedUsable && !anotherPreferred + Object expected = fallsBack ? NAMED : (was.failed ? 'failed' : was.chosen) + Object got = now.failed ? 'failed' : now.chosen + Map wasCreated = ((List) was.created).countBy { it } + String overCreated = ((List) now.created).countBy { it }.find { String name, Integer count -> + count > (wasCreated[name] ?: 0) + (fallsBack && name == NAMED ? 1 : 0) + }?.key + // the prototypes as in 8.0.0, and where 8.0.0 failed before them, as the probe's own resolution + Map prototypesMayCreate = ((fallsBack ? now.created : was.createdByPrototypes) ?: []).countBy { it } + String overCreatedByPrototypes = ((List) (now.createdByPrototypes ?: [])).countBy { it } + .find { String name, Integer count -> count > (prototypesMayCreate[name] ?: 0) }?.key + if (got != expected) { + mismatches << "${row}: got ${got}, expected ${expected} (8.0.0: ${was.failed ? 'failed' : was.chosen})".toString() + } + else if (overCreated) { + mismatches << "${row}: created ${now.created}, where 8.0.0 created ${was.created}".toString() + } + else if (overCreatedByPrototypes) { + mismatches << "${row}: prototypes created ${now.createdByPrototypes}, where 8.0.0 created ${was.createdByPrototypes}".toString() + } + else if (!now.failed && now.prototypes != (fallsBack ? [NAMED] * 3 : was.prototypes)) { + mismatches << "${row}: prototypes got ${now.prototypes}, where in 8.0.0 they got ${was.prototypes}".toString() + } + else if (!now.failed && !was.failed && now.self != was.self) { + mismatches << "${row}: grailsCacheManager got ${now.self}, where in 8.0.0 it got ${was.self}".toString() + } + else if (!now.failed && (fallsBack ? ((List) now.dependencies - ['customCacheKeyGenerator']) != [NAMED] : + now.dependencies != was.dependencies)) { + mismatches << "${row}: depends on ${now.dependencies}, where 8.0.0 depended on ${was.dependencies}".toString() + } + } + mismatches == [] + } + + void 'cache managers registered as singletons, without a bean definition, are judged as Spring judges them'() { + given: + CacheManager preferred = new HighPriorityCacheManager() + GenericApplicationContext besidePriority = context([(NAMED): 'plain'], [:], [], true) { GenericApplicationContext it -> + it.beanFactory.registerSingleton('preferred', preferred) + } + GenericApplicationContext besidePlain = context([(NAMED): 'plain'], [:], [], true) { GenericApplicationContext it -> + it.beanFactory.registerSingleton('other', new ConcurrentMapCacheManager()) + } + + expect: 'the one with a priority, as Spring chooses it, and grailsCacheManager where Spring cannot choose' + besidePriority.getBean('probe', CacheAware).grailsCacheManager.is(preferred) + besidePlain.getBean('probe', CacheAware).grailsCacheManager.is(besidePlain.getBean(NAMED)) + + cleanup: + besidePriority?.close() + besidePlain?.close() + } + + void 'a factory bean of new cache managers makes one for the injection, as in 8.0.0'() { + given: 'such a factory created first, beside a grailsCacheManager marked primary' + Map was = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], false) + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], true) + + expect: 'it is asked once for the injection, with the fallback as without it, and grailsCacheManager is injected' + ((List) was.created).count('factory') == 1 + ((List) now.created).count('factory') == 1 + now.chosen == NAMED && was.chosen == NAMED + } + + void 'prototype beans resolve their cache manager once, as in 8.0.0, so a factory bean of new cache managers is asked once'() { + given: 'such a factory created first, beside a grailsCacheManager marked primary, and three prototype cache-aware beans' + Map was = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], false) + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'primary'], true) + + expect: 'the factory is asked once for the first prototype, then the choice is reused' + was.prototypes == [NAMED] * 3 && now.prototypes == [NAMED] * 3 + ((List) now.createdByPrototypes).count('factory') == ((List) was.createdByPrototypes).count('factory') + ((List) now.createdByPrototypes).count('factory') == 1 + } + + void 'prototype beans given grailsCacheManager where Spring cannot choose keep it, and create nothing more'() { + given: 'a factory bean of new cache managers and grailsCacheManager, which Spring cannot choose between' + Map now = run([factory: 'prototypeFactoryBean', (NAMED): 'plain'], true) + + expect: 'the first prototype asks the factory once, and the rest reuse the choice' + now.chosen == NAMED + now.prototypes == [NAMED] * 3 + ((List) now.createdByPrototypes).count('factory') == 1 + } + + void 'a prototype bean registered again resolves its cache manager afresh, as in 8.0.0, where #arrangement#where'() { + when: 'a prototype is injected, a cache manager marked primary is added, and the prototype is registered again' + List was = copied ? reloadedWithCopiedResolver(row, false) : reloaded(row, false) + List now = copied ? reloadedWithCopiedResolver(row, true) : reloaded(row, true) + + then: 'the choice is kept until the prototype is registered again, and then made afresh' + now == expected + + and: 'as in 8.0.0, which kept its choice the same way; where it could not choose, it kept nothing to keep' + was == (row.first == 'plain' ? ['failed', 'preferred', 'preferred'] : expected) + + where: + arrangement | row | copied + 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] | false + 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] | false + 'Spring chooses grailsCacheManager' | [(NAMED): 'plain'] | true + 'it is grailsCacheManager by the fallback' | [(NAMED): 'plain', first: 'plain'] | true + expected = [NAMED, NAMED, 'preferred'] + where = copied ? ', in another bean factory with a copy of the resolver' : '' + } + + /** + * As {@link #reloaded}, in a bean factory of its own, with its own injection and a copy of the context's + * resolver, as {@code cloneIfNecessary} makes one for another bean factory. + */ + private List reloadedWithCopiedResolver(Map row, boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context([:], instances, [], withFallback) + DefaultListableBeanFactory factory = new DefaultListableBeanFactory() + factory.autowireCandidateResolver = context.defaultListableBeanFactory.autowireCandidateResolver.cloneIfNecessary() + AutowiredAnnotationBeanPostProcessor injection = new AutowiredAnnotationBeanPostProcessor() + injection.beanFactory = factory + factory.addBeanPostProcessor(injection) + Closure cacheManager = { String name, boolean primary -> + RootBeanDefinition definition = new RootBeanDefinition(CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances[name] = instance + instance + } as Supplier) + definition.primary = primary + definition + } + Closure prototype = { -> + RootBeanDefinition definition = new RootBeanDefinition(CacheAware) + definition.scope = BeanDefinition.SCOPE_PROTOTYPE + definition + } + row.keySet().each { String name -> factory.registerBeanDefinition(name, cacheManager(name, false)) } + factory.registerBeanDefinition('prototype', prototype()) + Closure inject = { -> + try { + nameOf(((CacheAware) factory.getBean('prototype')).grailsCacheManager, instances) + } + catch (BeansException ignored) { + 'failed' + } + } + try { + assert (factory.autowireCandidateResolver instanceof GrailsCacheManagerFallback.CandidateResolver) == withFallback + List got = [inject()] + factory.registerBeanDefinition('preferred', cacheManager('preferred', true)) + got << inject() + factory.registerBeanDefinition('prototype', prototype()) + got << inject() + return got + } + finally { + factory.destroySingletons() + context.close() + } + } + + /** What a prototype gets: at first, after a primary cache manager is added, and after it is registered again. */ + private List reloaded(Map row, boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context(row, instances, [], withFallback) + Closure inject = { -> + try { + nameOf(((CacheAware) context.getBean('prototype')).grailsCacheManager, instances) + } + catch (BeansException ignored) { + 'failed' + } + } + try { + List got = [inject()] + context.registerBean('preferred', CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances.preferred = instance + instance + } as Supplier, { BeanDefinition definition -> definition.primary = true } as BeanDefinitionCustomizer) + got << inject() + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) + got << inject() + return got + } + finally { + context.close() + } + } + + void 'a remembered cache manager that is removed and replaced is replaced in the memory too, as in 8.0.0'() { + when: 'a prototype gets the only cache manager, which is removed for another, and then a primary one is added' + List was = replaced(false) + List now = replaced(true) + + then: 'the replacement is remembered in its place, and kept when the primary one is added' + was == ['first', 'second', 'second'] + now == was + } + + /** What a prototype gets: from first, from second after first is removed, and after a primary one is added. */ + private List replaced(boolean withFallback) { + Map instances = [:] + GenericApplicationContext context = context([first: 'plain'], instances, [], withFallback) + Closure inject = { -> nameOf(((CacheAware) context.getBean('prototype')).grailsCacheManager, instances) } + Closure register = { String name, boolean primary -> + context.registerBean(name, CacheManager, { -> + CacheManager instance = new ConcurrentMapCacheManager() + instances[name] = instance + instance + } as Supplier, { BeanDefinition definition -> definition.primary = primary } as BeanDefinitionCustomizer) + null + } + try { + List got = [inject()] + context.removeBeanDefinition('first') + register('second', false) + got << inject() + register('third', true) + got << inject() + return got + } + finally { + context.close() + } + } + + void 'a remembered prototype cache manager made for its injection point gets one, as in 8.0.0'() { + given: 'a prototype cache manager whose factory method takes the injection point, and a prototype cache-aware bean' + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) + context.register(PerInjectionPoint) + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) + context.refresh() + + when: 'the prototype is injected again, from what is remembered' + List got = (1..3).collect { ((CacheAware) context.getBean('prototype')).grailsCacheManager } + + then: 'each injection made one, for the field' + got.every { it instanceof PerInjectionPointCacheManager && ((PerInjectionPointCacheManager) it).field?.name == GrailsCacheManagerFallback.FIELD_NAME } + got*.hashCode().unique().size() == 3 + + cleanup: + context?.close() + } + + void 'the injection Spring AOT generates resolves the field every time, as in 8.0.0'() { + given: 'a factory bean of new cache managers beside a primary grailsCacheManager, as in the prototype features' + Map was = aotResolved(false) + Map now = aotResolved(true) + + expect: 'each of three resolutions asks the factory, with the fallback as without it' + was.chosen == [NAMED] * 3 && now.chosen == [NAMED] * 3 + ((List) was.created).count('factory') == 3 + ((List) now.created).count('factory') == 3 + } + + /** Resolves the trait's field three times as AOT-generated code does, with a new injection point each time. */ + private Map aotResolved(boolean withFallback) { + Map instances = [:] + List created = [] + GenericApplicationContext context = context([factory: 'prototypeFactoryBean', (NAMED): 'primary'], instances, created, withFallback) + try { + int startup = created.size() + RegisteredBean prototype = RegisteredBean.of(context.defaultListableBeanFactory, 'prototype') + List chosen = (1..3).collect { + nameOf((CacheManager) AutowiredFieldValueResolver.forField(GrailsCacheManagerFallback.FIELD_NAME).resolve(prototype), instances) + } + return [chosen: chosen, created: new ArrayList(created.subList(startup, created.size()))] + } + finally { + context.close() + } + } + + void 'a cache manager injected anywhere else is left as Spring resolves it'() { + given: 'two cache managers Spring cannot choose between, and a bean of the application\'s own that injects one' + GenericApplicationContext context = context([(NAMED): 'plain', first: 'plain'], [:], [], true) { GenericApplicationContext it -> + it.registerBean('own', OwnInjection, { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer) + } + + when: + context.getBean('own') + + then: 'it fails as it did, while the cache-aware class gets grailsCacheManager' + UnsatisfiedDependencyException e = thrown() + e.cause instanceof NoUniqueBeanDefinitionException + context.getBean('probe', CacheAware).grailsCacheManager.is(context.getBean(NAMED)) + + cleanup: + context?.close() + } + + void 'the resolver is installed once, and copied as itself'() { + given: + GenericApplicationContext context = context([(NAMED): 'plain'], [:], [], true) + + when: 'post-processed again' + new GrailsCacheManagerFallback().postProcessBeanFactory(context.beanFactory) + AutowireCandidateResolver resolver = context.defaultListableBeanFactory.autowireCandidateResolver + + then: + resolver instanceof GrailsCacheManagerFallback.CandidateResolver + !(resolver.@delegate instanceof GrailsCacheManagerFallback.CandidateResolver) + resolver.cloneIfNecessary() instanceof GrailsCacheManagerFallback.CandidateResolver + + cleanup: + context?.close() + } + + private Map run(Map row, boolean withFallback) { + Map instances = [:] + List created = [] + List atStartup = [] + Map result = [failed: false, failedAtStartup: false] + GenericApplicationContext started = null + try { + try { + // a cyclic grailsCacheManager has the probe injected while the context starts + started = context(row, instances, created, withFallback) + } + catch (BeansException e) { + result.failedAtStartup = true + throw e + } + atStartup.addAll(created) + CacheManager chosen = ((CacheAware) started.getBean('probe')).grailsCacheManager + result.chosen = nameOf(chosen, instances) + if (row[NAMED] == 'cacheAware') { + result.self = nameOf(((GrailsCacheManagerAware) started.getBean(NAMED)).grailsCacheManager, instances) + } + result.dependencies = (started.beanFactory.getDependenciesForBean('probe') as List).sort() + int beforePrototypes = created.size() + result.prototypes = (1..3).collect { nameOf(((CacheAware) started.getBean('prototype')).grailsCacheManager, instances) } + result.createdByPrototypes = new ArrayList(created.subList(beforePrototypes, created.size())) + created.subList(beforePrototypes, created.size()).clear() + } + catch (BeansException ignored) { + result.failed = true + } + finally { + started?.close() + } + // what was created after startup, each creation counted, as a list difference would drop repeats + result.created = new ArrayList(created.subList(atStartup.size(), created.size())) + result + } + + private static String nameOf(CacheManager cacheManager, Map instances) { + cacheManager == null ? null : instances.find { String name, CacheManager instance -> instance.is(cacheManager) }?.key + } + + private GenericApplicationContext context(Map row, Map instances, + List created, boolean withFallback, + Closure beforeRefresh = null) { + GenericApplicationContext context = new GenericApplicationContext() + AnnotationConfigUtils.registerAnnotationConfigProcessors(context) + if (withFallback) { + context.addBeanFactoryPostProcessor(new GrailsCacheManagerFallback()) + } + row.each { String name, String kind -> + if (kind == 'wrongType') { + context.registerBean(name, String, { -> 'not a cache manager' } as Supplier) + return + } + Class type = kind in ['priority', 'priorityOnObject', 'factoryBean', 'createdByKeyGenerator'] ? + HighPriorityCacheManager : (kind == 'cacheAware' ? CacheAwareCacheManager : ConcurrentMapCacheManager) + Supplier supplier = { -> + if (kind == 'cyclic') { + context.getBean('probe') + } + created << name + // a factory method that returns null makes Spring's null bean + CacheManager instance = kind == 'nullBean' ? null : type.getDeclaredConstructor().newInstance() + instances[name] = instance + instance + } as Supplier + if (kind in ['factoryBean', 'prototypeFactoryBean']) { + boolean singleton = kind == 'factoryBean' + context.registerBean(name, ProductFactoryBean, { -> new ProductFactoryBean(supplier, singleton) } as Supplier) + return + } + // declared as a plain CacheManager, as a factory method would declare it, so only the object has the priority + Class declared = kind in ['priorityOnObject', 'createdByKeyGenerator'] ? CacheManager : type + BeanDefinitionCustomizer customizer = { BeanDefinition definition -> + AbstractBeanDefinition bean = (AbstractBeanDefinition) definition + bean.primary = kind == 'primary' + bean.lazyInit = kind in ['lazy', 'createdByKeyGenerator'] + bean.autowireCandidate = kind != 'notCandidate' + bean.fallback = kind == 'fallback' + bean.defaultCandidate = kind != 'notDefault' + } as BeanDefinitionCustomizer + context.registerBean(name, (Class) declared, supplier, customizer) + } + BeanDefinitionCustomizer lazy = { BeanDefinition definition -> definition.lazyInit = true } as BeanDefinitionCustomizer + List forKeyGenerator = row.findAll { String name, String kind -> kind == 'createdByKeyGenerator' }*.key + if (forKeyGenerator) { + // injected into the cache-aware bean before its cache manager, and creating cache managers when it is + context.registerBean('customCacheKeyGenerator', GrailsCacheKeyGenerator, { -> + forKeyGenerator.each { String name -> context.getBean(name) } + new CustomCacheKeyGenerator() + } as Supplier, lazy) + } + context.registerBean('probe', CacheAware, lazy) + context.registerBean('prototype', CacheAware, + { BeanDefinition definition -> definition.scope = BeanDefinition.SCOPE_PROTOTYPE } as BeanDefinitionCustomizer) + beforeRefresh?.call(context) + context.refresh() + context + } + + private static List> arrangements() { + List> others = [[:]] + OTHER_KINDS.each { String first -> others << [first: first] } + OTHER_KINDS.each { String first -> OTHER_KINDS.each { String second -> others << [first: first, second: second] } } + NAMED_KINDS.collectMany { String named -> + others.collect { Map other -> named == 'absent' ? other : ([(NAMED): named] + other) } + } + } + + static class CacheAware implements GrailsCacheManagerAware { + } + + /** A bean of the application's own that injects a cache manager by type, as the trait does. */ + static class OwnInjection { + @Autowired(required = false) + CacheManager someCacheManager + } + + @Priority(1) + static class HighPriorityCacheManager extends ConcurrentMapCacheManager { + } + + /** A cache manager made for the injection point it is injected into. */ + static class PerInjectionPointCacheManager extends ConcurrentMapCacheManager { + java.lang.reflect.Field field + } + + @Configuration(proxyBeanMethods = false) + static class PerInjectionPoint { + @Bean + @Scope(BeanDefinition.SCOPE_PROTOTYPE) + static CacheManager perInjectionPoint(InjectionPoint injectionPoint) { + new PerInjectionPointCacheManager(field: injectionPoint.field) + } + } + + /** A grailsCacheManager that is cache-aware itself, which Spring leaves out of the candidates for its own field. */ + static class CacheAwareCacheManager extends ConcurrentMapCacheManager implements GrailsCacheManagerAware { + } + + /** A factory bean that names only CacheManager as its type, making one cache manager or a new one each time. */ + static class ProductFactoryBean implements FactoryBean { + + private final Supplier product + + private final boolean singleton + + ProductFactoryBean(Supplier product, boolean singleton) { + this.product = product + this.singleton = singleton + } + + @Override + boolean isSingleton() { + singleton + } + + @Override + CacheManager getObject() { + product.get() + } + + @Override + Class getObjectType() { + CacheManager + } + } +} diff --git a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc index 6b711519930..12f068d1bec 100644 --- a/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc +++ b/grails-doc/src/en/guide/cache/cacheUsage/cacheManager.adoc @@ -20,3 +20,9 @@ under the License. The plugin registers an instance of the link:{springapi}/org/springframework/cache/CacheManager.html[CacheManager] interface as the `grailsCacheManager` Spring bean, so it's easy to access using dependency injection. The most common method you would call on the `grailsCacheManager` is `getCache(String name)` to access a link:{springapi}/org/springframework/cache/Cache.html[Cache] instance programmatically. This shouldn't be needed often however. From the `Cache` instance you can also access the underlying cache implementation using `cache.getNativeCache()`. + +The cache annotations and the cache tags cache with the `grailsCacheManager` bean. A cache provider plugin replaces it by defining a bean of that name, and an application can do the same with a `GrailsCacheManager` of its own. + +The annotations receive their cache manager by type. Where the application context has another cache manager too, Spring uses the one marked primary, or the one with the highest `@Priority`, and where there is neither, `grailsCacheManager`. That other cache manager might be one the application defines for Spring's own caching, or the one the Spring Security plugin defines when `cacheUsers` is set. + +A cache manager may have no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with. The annotated method then runs uncached, and a warning names the class and the cache once for each cache manager. diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 7b66b6dc9f6..95798a7576e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5005,3 +5005,9 @@ As of Grails 8.0.1, with `grails.plugin.springsecurity.rest.token.storage.jwt.us * For an encrypted JWT, `JwtService.parse` and the `accessTokenJwt` property of an `AccessToken` now return a `grails.plugin.springsecurity.rest.token.generation.jwt.NestedJwt` instead of a `com.nimbusds.jwt.EncryptedJWT`. Its claims are those of the signed JWT inside, its header is that of the encrypted JWT, and it serializes to the token. * With encrypted JWTs enabled, a signed JWT is rejected as an invalid token, and with signed JWTs, an encrypted JWT is. Previously such a token failed with a `NullPointerException`. * An encrypted JWT whose content encryption key is encrypted with `RSA1_5` is rejected unless `grails.plugin.springsecurity.rest.token.generation.jwt.jweAlgorithm` is `RSA1_5`. The plugin passes that setting to the new `jweAlgorithm` property of `JwtService`. A `jwtService` bean that an application defines itself accepts `RSA1_5` as before, unless the application sets that property too. + +==== A Second Cache Manager No Longer Stops a Cached Application From Starting + +The cache annotations receive their cache manager by type. Grails 8.0.0 failed to start when the application context had a second `CacheManager` beside the plugin's `grailsCacheManager` and neither was marked primary or had a `@Priority`, which is what happens when the Spring Security plugin's `cacheUsers` is set. Spring now uses `grailsCacheManager` there. Where one of them is marked primary or has a `@Priority`, Spring uses that one, as before, and with caching turned off (`grails.cache.enabled: false`) nothing changes. This applies to classes compiled against Grails 8.0.0 too, so plugins need not be recompiled. + +Where the cache manager has no cache of the name an annotation gives, as a `JCacheCacheManager` has none it was not configured with, the annotated method now runs uncached, and a warning names the class and the cache once. Grails 8.0.0 failed with a `NullPointerException` on each call. This applies to classes compiled against this version. diff --git a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md index f9391b4c42d..15e60cfb3dc 100644 --- a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md +++ b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md @@ -1664,6 +1664,11 @@ java -XX:MaxRAMPercentage=60.0 -XX:MaxMetaspaceSize=256m -Dgrails.env=prod -jar - **A placeholder that names a configuration list no longer fails to resolve, and a list of plain values resolves to its elements.** Search for `@Value('${...}')` and other `${...}` placeholders that name a list in `application.yml` or `application.groovy`. A placeholder that names a list of objects is now left as written, so the injection point receives the placeholder text, or its default when it has one; in 8.0.0 a placeholder without a default failed to resolve. A list of plain values only, such as `names: [a, b]`, is now presented by its indexed names too, and a placeholder that names it resolves to its elements joined by commas. Read a list of objects through `grailsApplication.config` or bind it. +## Cache Plugin Beside Another Cache Manager + +- **A second `CacheManager` beside the cache plugin's `grailsCacheManager` no longer stops a cached application from starting.** Search for `CacheManager` beans the application or its plugins define, and for `cacheUsers` in the Spring Security plugin's configuration, which defines one named `cacheManager`. Where neither cache manager is marked primary or has a `@Priority`, Grails 8.0.0 failed to create `grailsCacheAdminService` and every class with a cached method; Spring now uses `grailsCacheManager` there, also for classes compiled against 8.0.0. A cache manager marked primary or with a `@Priority` is still used, and nothing changes with `grails.cache.enabled: false`. +- **A method whose cache the cache manager does not have runs uncached.** A cache manager answers null for a cache name it has no cache of, as a `JCacheCacheManager` does for a cache it was not configured with, and in Grails 8.0.0 every call of such a `@Cacheable`, `@CachePut` or `@CacheEvict` method failed with a `NullPointerException`. Classes compiled against 8.0.1 run uncached there, and a warning names the class and the cache once. Configure the cache in that cache manager to cache with it. + # After the Upgrade ## Verification Checklist