Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Config: injection verification during the native image build #36169

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.CreationException;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigValue;
import org.eclipse.microprofile.config.inject.ConfigProperties;
import org.eclipse.microprofile.config.inject.ConfigProperty;
Expand All @@ -42,10 +41,8 @@
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.ParameterizedType;
import org.jboss.jandex.Type;
import org.jboss.jandex.Type.Kind;
import org.jboss.logging.Logger;

import io.quarkus.arc.Unremovable;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem.BeanConfiguratorBuildItem;
Expand All @@ -67,9 +64,9 @@
import io.quarkus.deployment.builditem.ConfigPropertiesBuildItem;
import io.quarkus.deployment.builditem.ConfigurationBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.RunTimeConfigurationDefaultBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.configuration.definition.RootDefinition;
import io.quarkus.deployment.pkg.PackageConfig;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.runtime.annotations.ConfigPhase;
Expand All @@ -80,14 +77,11 @@
* MicroProfile Config related build steps.
*/
public class ConfigBuildStep {
private static final Logger LOGGER = Logger.getLogger(ConfigBuildStep.class.getName());

private static final DotName MP_CONFIG = DotName.createSimple(Config.class.getName());
private static final DotName MP_CONFIG_PROPERTY_NAME = DotName.createSimple(ConfigProperty.class.getName());
static final DotName MP_CONFIG_PROPERTY_NAME = DotName.createSimple(ConfigProperty.class.getName());
private static final DotName MP_CONFIG_PROPERTIES_NAME = DotName.createSimple(ConfigProperties.class.getName());
private static final DotName MP_CONFIG_VALUE_NAME = DotName.createSimple(ConfigValue.class.getName());

private static final DotName SR_CONFIG = DotName.createSimple(io.smallrye.config.SmallRyeConfig.class.getName());
private static final DotName SR_CONFIG_VALUE_NAME = DotName.createSimple(io.smallrye.config.ConfigValue.class.getName());

private static final DotName MAP_NAME = DotName.createSimple(Map.class.getName());
Expand Down Expand Up @@ -290,6 +284,7 @@ void registerConfigMappingsBean(
BeanRegistrationPhaseBuildItem beanRegistration,
List<ConfigClassBuildItem> configClasses,
CombinedIndexBuildItem combinedIndex,
PackageConfig packageConfig,
BuildProducer<BeanConfiguratorBuildItem> beanConfigurator) {

if (configClasses.isEmpty()) {
Expand Down Expand Up @@ -323,7 +318,8 @@ void registerConfigMappingsBean(
.creator(ConfigMappingCreator.class)
.addInjectionPoint(ClassType.create(DotNames.INJECTION_POINT))
.param("type", configClass.getConfigClass())
.param("prefix", configClass.getPrefix());
.param("prefix", configClass.getPrefix())
.param("nativeBuild", packageConfig.type.equalsIgnoreCase(PackageConfig.BuiltInType.NATIVE.getValue()));

if (configClass.getConfigClass().isAnnotationPresent(Unremovable.class)) {
bean.unremovable();
Expand All @@ -338,6 +334,7 @@ void registerConfigPropertiesBean(
BeanRegistrationPhaseBuildItem beanRegistration,
List<ConfigClassBuildItem> configClasses,
CombinedIndexBuildItem combinedIndex,
PackageConfig packageConfig,
BuildProducer<BeanConfiguratorBuildItem> beanConfigurator) {

if (configClasses.isEmpty()) {
Expand Down Expand Up @@ -371,7 +368,9 @@ void registerConfigPropertiesBean(
.creator(ConfigMappingCreator.class)
.addInjectionPoint(ClassType.create(DotNames.INJECTION_POINT))
.param("type", configClass.getConfigClass())
.param("prefix", configClass.getPrefix())));
.param("prefix", configClass.getPrefix())
.param("nativeBuild",
packageConfig.type.equalsIgnoreCase(PackageConfig.BuiltInType.NATIVE.getValue()))));
}
}

Expand Down Expand Up @@ -474,67 +473,6 @@ void validateConfigPropertiesInjectionPoints(
toRegister.forEach(configProperties::produce);
}

@BuildStep
void warnStaticInitInjectionPoints(
CombinedIndexBuildItem indexBuildItem,
ValidationPhaseBuildItem validationPhase,
List<ConfigClassBuildItem> configClasses,
List<ConfigInjectionStaticInitBuildItem> configInjectionStaticInit,
BuildProducer<RunTimeConfigurationDefaultBuildItem> runTimeConfigurationDefault) {

// Add here annotated classes that are initialized during static init
Set<DotName> declaringClassCandidates = configInjectionStaticInit.stream()
.map(ConfigInjectionStaticInitBuildItem::getDeclaringCandidate).collect(toSet());

Set<Type> configClassesTypes = configClasses.stream().map(ConfigClassBuildItem::getTypes).flatMap(Collection::stream)
.collect(toSet());

for (InjectionPointInfo injectionPoint : validationPhase.getContext().getInjectionPoints()) {
if (injectionPoint.getType().name().equals(DotNames.INSTANCE)) {
continue;
}

Type type = Type.create(injectionPoint.getRequiredType().name(), Type.Kind.CLASS);
DotName injectionTypeName = null;
if (type.name().equals(MP_CONFIG) || type.name().equals(SR_CONFIG)) {
injectionTypeName = type.name();
} else if (injectionPoint.getRequiredQualifier(MP_CONFIG_PROPERTY_NAME) != null) {
injectionTypeName = MP_CONFIG_PROPERTY_NAME;
} else if (configClassesTypes.contains(type)) {
injectionTypeName = type.name();
}

if (injectionTypeName != null) {
AnnotationTarget target = injectionPoint.getTarget();
if (FIELD.equals(target.kind())) {
FieldInfo field = target.asField();
ClassInfo declaringClass = field.declaringClass();
Map<DotName, List<AnnotationInstance>> annotationsMap = declaringClass.annotationsMap();
for (DotName declaringClassCandidate : declaringClassCandidates) {
List<AnnotationInstance> annotationInstances = annotationsMap.get(declaringClassCandidate);
if (annotationInstances != null && annotationInstances.size() == 1) {
AnnotationInstance annotationInstance = annotationInstances.get(0);
if (annotationInstance.target().equals(declaringClass)) {
LOGGER.warn("Directly injecting a " +
injectionTypeName +
" into a " +
declaringClassCandidate +
" may lead to unexpected results. To ensure proper results, please " +
"change the type of the field to " +
ParameterizedType.create(DotNames.INSTANCE, new Type[] { type }, null) +
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see this earlier version of the check took into account the type being injected in the error message (i.e. it would suggest Instance<MyConfig> instead of Instance<String>, IIUC).

Would it make sense to still do that with the new approach, or is it too complex to be worth it?

". Offending field is '" +
field.name() +
"' of class '" +
field.declaringClass() +
"'");
}
}
}
}
}
}
}

@BuildStep
@Record(RUNTIME_INIT)
void registerConfigClasses(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@

import io.quarkus.builder.item.MultiBuildItem;

/**
*
* @deprecated This build item is not used anymore
*/
@Deprecated(forRemoval = true)
public final class ConfigInjectionStaticInitBuildItem extends MultiBuildItem {

private final DotName declaringCandidate;

public ConfigInjectionStaticInitBuildItem(final DotName declaringCandidate) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package io.quarkus.arc.deployment;

import java.util.HashSet;
import java.util.Set;

import jakarta.inject.Singleton;

import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;

import io.quarkus.arc.processor.AnnotationsTransformer;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.arc.processor.InjectionPointInfo;
import io.quarkus.arc.runtime.NativeBuildConfigCheck;
import io.quarkus.arc.runtime.NativeBuildConfigCheckInterceptor;
import io.quarkus.arc.runtime.NativeBuildConfigContext;
import io.quarkus.arc.runtime.NativeBuildConfigContextCreator;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.ConfigurationBuildItem;
import io.quarkus.deployment.pkg.steps.NativeBuild;

public class NativeBuildConfigSteps {

@BuildStep(onlyIf = NativeBuild.class)
SyntheticBeanBuildItem registerNativeBuildConfigContext(ConfigurationBuildItem config,
BeanDiscoveryFinishedBuildItem beanDiscoveryFinished) {

// Collect all @ConfigProperty injection points
Set<String> injectedProperties = new HashSet<>();
for (InjectionPointInfo injectionPoint : beanDiscoveryFinished.getInjectionPoints()) {
if (injectionPoint.hasDefaultedQualifier()) {
continue;
}
AnnotationInstance configProperty = injectionPoint.getRequiredQualifier(ConfigBuildStep.MP_CONFIG_PROPERTY_NAME);
if (configProperty != null) {
injectedProperties.add(configProperty.value("name").asString());
}
}

// Retain only BUILD_AND_RUN_TIME_FIXED properties
injectedProperties.retainAll(config.getReadResult().getBuildTimeRunTimeValues().keySet());

return SyntheticBeanBuildItem.configure(NativeBuildConfigContext.class)
.param(
"buildAndRunTimeFixed",
injectedProperties.toArray(String[]::new))
.creator(NativeBuildConfigContextCreator.class)
.scope(Singleton.class)
.done();

}

@BuildStep(onlyIf = NativeBuild.class)
AdditionalBeanBuildItem registerBeans() {
return AdditionalBeanBuildItem.builder().addBeanClasses(NativeBuildConfigCheckInterceptor.class,
NativeBuildConfigCheck.class).build();
}

@BuildStep(onlyIf = NativeBuild.class)
AnnotationsTransformerBuildItem transformConfigProducer() {
DotName configProducerName = DotName.createSimple("io.smallrye.config.inject.ConfigProducer");

return new AnnotationsTransformerBuildItem(AnnotationsTransformer.appliedToMethod().whenMethod(m -> {
// Apply to all producer methods declared on io.smallrye.config.inject.ConfigProducer
return m.declaringClass().name().equals(configProducerName)
&& m.hasAnnotation(DotNames.PRODUCES)
&& m.hasAnnotation(ConfigBuildStep.MP_CONFIG_PROPERTY_NAME);
}).thenTransform(t -> {
t.add(NativeBuildConfigCheck.class);
}));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.quarkus.arc.test.config.nativebuild;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Singleton;

import org.eclipse.microprofile.config.inject.ConfigProperty;

@Singleton
public class Fail {

@ConfigProperty(name = "foo", defaultValue = "bar")
String value;

// triggers init during static init of native build
void init(@Observes @Initialized(ApplicationScoped.class) Object event) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.quarkus.arc.test.config.nativebuild;

import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusProdModeTest;

public class NativeBuildConfigInjectionFailTest {

@RegisterExtension
static final QuarkusProdModeTest TEST = new QuarkusProdModeTest()
.setBuildNative(true)
.withApplicationRoot(
root -> root.addClass(Fail.class))
// ImageGenerationFailureException is private
.setExpectedException(RuntimeException.class);

@Test
void test() {
fail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.quarkus.arc.test.config.nativebuild;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusProdModeTest;

public class NativeBuildConfigInjectionOkTest {

@RegisterExtension
static final QuarkusProdModeTest TEST = new QuarkusProdModeTest()
.setBuildNative(true)
.withApplicationRoot(
root -> root.addClass(Ok.class));

@Test
void test() {
}
}
yrodiere marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package io.quarkus.arc.test.config.nativebuild;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Singleton;

import org.eclipse.microprofile.config.inject.ConfigProperty;

import io.quarkus.arc.config.NativeBuildTime;

@Singleton
public class Ok {

@NativeBuildTime
@ConfigProperty(name = "foo", defaultValue = "bar")
String value;

// triggers init during static init of native build
void init(@Observes @Initialized(ApplicationScoped.class) Object event) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.quarkus.arc.config;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
* A config property injected during the static initialization phase of a native image build may result in unexpected errors
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* A config property injected during the static initialization phase of a native image build may result in unexpected errors
* Allows a configuration property injection point to retrieve values during static initialization.
* <p>
* A config property injected during the static initialization phase of a native image build may result in unexpected errors

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should improve the wording here, as it's not only about injecting properties.

* because the injected value was obtained at build time and cannot be updated at runtime.
* <p>
* If it's intentional and expected then use this annotation to eliminate the false positive.
*/
@Retention(RUNTIME)
@Target({ FIELD, PARAMETER })
public @interface NativeBuildTime {

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.lang.annotation.Annotation;
import java.util.Optional;
import java.util.Set;

import jakarta.enterprise.inject.spi.Annotated;
import jakarta.enterprise.inject.spi.InjectionPoint;
Expand All @@ -23,6 +24,10 @@ public Object create(SyntheticCreationalContext<Object> context) {
throw new IllegalStateException("No current injection point found");
}

if ((boolean) context.getParams().get("nativeBuild")) {
NativeBuildConfigCheckInterceptor.verifyCurrentImageMode(Set.of());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC the Set is empty here because we assume none of the properties being injected are "build and runtime fixed"... but can't a config mapping be completely "build and runtime fixed"? If so we'd want to skip this check, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, a ConfigRoot defined as a config mapping is something I need to check.

Because we do register a synthetic bean for any BUILD_AND_RUN_TIME_FIXED/RUN_TIME config root here and my guess would be that an injected config root with a config mapping would result in an ambiguous dependency error...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI it's not a problem because a config root implemented as a config mapping is not considered a RootDefinition...

}

Class<?> interfaceType = (Class<?>) context.getParams().get("type");
String prefix = (String) context.getParams().get("prefix");

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.quarkus.arc.runtime;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import jakarta.interceptor.InterceptorBinding;

/**
* Interceptor binding for {@link NativeBuildConfigCheckInterceptor}.
*/
@InterceptorBinding
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface NativeBuildConfigCheck {

}
Loading