christophd commented on code in PR #27440: URL: https://github.com/apache/camel/pull/27440#discussion_r4198604047
########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureConfiguration.java: ########## @@ -0,0 +1,206 @@ +/* + * 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 + * + * http://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.apache.camel.component.openfeature; + +import dev.openfeature.sdk.MutableContext; +import org.apache.camel.Exchange; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriParams; + +@UriParams +public class OpenFeatureConfiguration implements Cloneable { + + @UriParam(label = "common", + description = "The feature flag key to evaluate. Can be overridden per message via the CamelOpenFeatureFlagKey header.") + private String flagKey; + + @UriParam(label = "common", defaultValue = "false", + description = "Default value when flag evaluation fails. When evaluationType is not set," + + " also determines the evaluation type: \"true\" or \"false\" (case-insensitive)" + + " selects boolean evaluation, any other value selects string evaluation.") + private String defaultValue = "false"; + + @UriParam(label = "common", enums = "boolean,variant", + description = "The evaluation type. When set to 'boolean', boolean evaluation is used (getBooleanValue)." + + " When set to 'variant', string evaluation is used (getStringValue)." + + " When not set, the type is inferred from defaultValue.") + private String evaluationType; + + @UriParam(label = "producer", + description = "Store the evaluation result in this exchange property, preserving the original message body.") + private String resultProperty; + + @UriParam(label = "common", description = "Remote flagd service host. When set, the flagd RPC resolver is used.") + private String host; + + @UriParam(label = "common", defaultValue = "8013", description = "Remote flagd service port.") + private int port = 8013; + + @UriParam(label = "common", + description = "A JSON object defining feature flags in flagd format (inline). Mutually exclusive with flagsResource.") + private String flags; + + @UriParam(label = "common", + description = "Camel resource URI pointing to a feature flag definition file in flagd format." + + " Mutually exclusive with flags and provider.") + private String flagsResource; + + @UriParam(label = "common", + description = "Bean reference to a custom FeatureProvider (e.g. #myProvider)." + + " Mutually exclusive with flags and flagsResource.") + private String provider; + + public String getFlagKey() { + return flagKey; + } + + /** The feature flag key to evaluate. */ + public void setFlagKey(String flagKey) { + this.flagKey = flagKey; + } + + public String getDefaultValue() { + return defaultValue; + } + + /** + * Default value when flag evaluation fails. When evaluationType is not set, also determines the evaluation type: + * "true" or "false" (case-insensitive) selects boolean evaluation, any other value selects string evaluation. + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getEvaluationType() { + return evaluationType; + } + + /** + * The evaluation type. When set to 'boolean', boolean evaluation is used. When set to 'variant', string evaluation + * is used. When not set, the type is inferred from defaultValue. + */ + public void setEvaluationType(String evaluationType) { + this.evaluationType = evaluationType; + } + + public String getResultProperty() { + return resultProperty; + } + + /** Store the evaluation result in this exchange property, preserving the original message body. */ + public void setResultProperty(String resultProperty) { + this.resultProperty = resultProperty; + } + + public String getHost() { + return host; + } + + /** Remote flagd service host. When set, the flagd RPC resolver is used. */ + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + /** Remote flagd service port. */ + public void setPort(int port) { + this.port = port; + } + + public String getFlags() { + return flags; + } + + /** A JSON object defining feature flags in flagd format (inline). Mutually exclusive with flagsResource. */ + public void setFlags(String flags) { + this.flags = flags; + } + + public String getFlagsResource() { + return flagsResource; + } + + /** + * Camel resource URI pointing to a feature flag definition file in flagd format. Mutually exclusive with flags and + * provider. + */ + public void setFlagsResource(String flagsResource) { + this.flagsResource = flagsResource; + } + + public String getProvider() { + return provider; + } + + /** + * Bean reference to a custom FeatureProvider (e.g. #myProvider). Mutually exclusive with flags and flagsResource. + */ + public void setProvider(String provider) { + this.provider = provider; + } + + public boolean isBooleanEvaluation(Exchange exchange, MutableContext ctx) { + String evalType = exchange.getIn().getHeader(OpenFeatureConstants.EVALUATION_TYPE, String.class); + if (evalType == null) { + evalType = exchange.getProperty(OpenFeatureConstants.EVALUATION_TYPE, String.class); + } + if (evalType == null) { + evalType = evaluationType; + } + + if ("boolean".equalsIgnoreCase(evalType)) { + return true; + } + if ("variant".equalsIgnoreCase(evalType)) { + return false; + } + if (!ctx.asMap().isEmpty()) { Review Comment: Fixed. `isBooleanEvaluation` no longer considers context — it now derives the type only from `evaluationType` and `defaultValue`. Added `targeted-boolean` flag definition (with `if`/`in` targeting rule) and three producer tests that evaluate a boolean flag with targeting key and Map body: `testBooleanFlagWithTargetingKeyReturnsBooleanNotString`, `testBooleanFlagWithTargetingKeyDefaultVariant`, and `testBooleanFlagWithMapBodyReturnsBoolean` — all assert the result is `Boolean.class`, not String. ########## components/camel-openfeature/src/main/java/org/apache/camel/language/openfeature/OpenFeatureLanguage.java: ########## @@ -0,0 +1,171 @@ +/* + * 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 + * + * http://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.apache.camel.language.openfeature; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Expression; +import org.apache.camel.Predicate; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.component.openfeature.OpenFeatureConstants; +import org.apache.camel.component.openfeature.OpenFeatureEndpoint; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.annotations.Language; +import org.apache.camel.support.ExpressionAdapter; +import org.apache.camel.support.ExpressionToPredicateAdapter; +import org.apache.camel.support.LanguageSupport; + +/** Evaluates a feature flag as a boolean predicate for use in EIP constructs such as filter, choice, and validate. */ +@Language(value = "openfeature", modelName = "language") +@Metadata(title = "OpenFeature", description = "Evaluate a feature flag as a boolean predicate", + label = "language,cloud", firstVersion = "4.23.0") +public class OpenFeatureLanguage extends LanguageSupport { + + private String endpoint = "openfeature:flags"; + + @Override + public Predicate createPredicate(String expression) { + return createPredicate(expression, null); + } + + @SuppressWarnings("unchecked") + @Override + public Predicate createPredicate(String expression, Object[] properties) { + validateExpression(expression); + Evaluation answer = new Evaluation( + expression, + property(String.class, properties, 0, endpoint), + property(String.class, properties, 1, null), + property(Map.class, properties, 2, null), + property(String.class, properties, 3, "boolean")); + if (getCamelContext() != null) { + answer.init(getCamelContext()); + } + return ExpressionToPredicateAdapter.toPredicate(answer); + } + + @Override + public Expression createExpression(String expression) { + return createExpression(expression, new Object[] {}); + } + + @SuppressWarnings("unchecked") + @Override + public ExpressionAdapter createExpression(String expression, Object[] properties) { + validateExpression(expression); + Evaluation answer = new Evaluation( + expression, + property(String.class, properties, 0, endpoint), + property(String.class, properties, 1, null), + property(Map.class, properties, 2, null), + property(String.class, properties, 3, "variant")); + if (getCamelContext() != null) { + answer.init(getCamelContext()); + } + return answer; + } + + public boolean validateExpression(String expression) { + if (expression == null || expression.isBlank()) { + throw new IllegalArgumentException("OpenFeature flag key must not be null or blank"); + } + return true; + } + + public String getEndpoint() { + return endpoint; + } + + /** Managed endpoint URI. Defaults to openfeature:flags, inheriting camel.component.openfeature settings. */ + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + private static final class Evaluation extends ExpressionAdapter { + private final String flagKey; + private final String endpointUri; + private final String targetingKey; + private final Map<String, Object> contextMap; + private OpenFeatureEndpoint endpoint; + private boolean useFlagKeyHeader; + private String evaluationType; + + private Evaluation(String flagKey, String endpointUri, String targetingKey, + Map<String, Object> contextMap, String evaluationType) { + this.flagKey = flagKey; + this.endpointUri = endpointUri; + this.targetingKey = targetingKey; + this.contextMap = contextMap; + this.evaluationType = evaluationType; + } + + @Override + public void init(CamelContext context) { + super.init(context); + if (endpointUri == null || !endpointUri.startsWith("openfeature:")) { + throw new IllegalArgumentException("OpenFeature language endpoint must be an openfeature: URI"); + } + String uri = endpointUri; + if (uri.contains("flagKey=")) { + useFlagKeyHeader = true; + } else { + uri += (uri.contains("?") ? "&" : "?") + "flagKey=" + flagKey; + useFlagKeyHeader = false; + } + endpoint = context.getEndpoint(uri, OpenFeatureEndpoint.class); + } + + @Override + public <T> T evaluate(Exchange exchange, Class<T> type) { + if (Boolean.class.isAssignableFrom(type)) { + evaluationType = "boolean"; + } + return super.evaluate(exchange, type); + } + + @Override + public Object evaluate(Exchange exchange) { + try { + if (endpoint == null) { + throw new IllegalStateException("OpenFeature expression must be initialized"); + } + if (useFlagKeyHeader) { Review Comment: Fixed. Added an `OpenFeatureEndpoint.evaluate(Exchange, flagKey, evaluationType, targetingKey, contextMap)` overload that performs the evaluation without writing any exchange properties. The language now calls this directly — no properties are set, no URI manipulation with unencoded flag keys. Added `testLanguageDoesNotLeakIntoProducer` test: a `.filter().language("openfeature", ...)` followed by `.to("openfeature:...")` verifies the producer uses its own settings and no leftover properties are present. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,295 @@ +/* + * 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 + * + * http://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.apache.camel.component.openfeature; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Map; + +import dev.openfeature.contrib.providers.flagd.Config; +import dev.openfeature.contrib.providers.flagd.FlagdOptions; +import dev.openfeature.contrib.providers.flagd.FlagdProvider; +import dev.openfeature.sdk.Client; +import dev.openfeature.sdk.FeatureProvider; +import dev.openfeature.sdk.MutableContext; +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; +import org.apache.camel.support.ResourceHelper; + +/** Evaluate feature flags using the OpenFeature specification with flagd. */ +@UriEndpoint(firstVersion = "4.23.0", scheme = "openfeature", title = "OpenFeature", syntax = "openfeature:domain", + producerOnly = true, category = { Category.CORE }) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final String DEFAULT_PROVIDER_BEAN = "flags"; + + @UriPath + @Metadata(required = true) + private String domain; + + @UriParam + private OpenFeatureConfiguration configuration; + + private volatile Client client; + private volatile FeatureProvider resolvedProvider; + private volatile File tempFlagFile; + private volatile boolean ownedProvider; + + public OpenFeatureEndpoint(String uri, OpenFeatureComponent component, String domain, + OpenFeatureConfiguration configuration) { + super(uri, component); + this.domain = domain; + this.configuration = configuration; + } + + @Override + public OpenFeatureComponent getComponent() { + return (OpenFeatureComponent) super.getComponent(); + } + + @Override + public Producer createProducer() { + return new OpenFeatureProducer(this); + } + + @Override + public Consumer createConsumer(Processor processor) { + throw new UnsupportedOperationException("OpenFeature is producer only"); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + configuration.validate(); + + if (domain == null || domain.isBlank()) { + throw new IllegalArgumentException("domain must not be blank"); + } + + FeatureProvider provider = resolveProvider(); + resolvedProvider = provider; + client = getComponent().registerProviderAndGetClient(domain, provider); + } + + @Override + protected void doStop() throws Exception { + client = null; + + if (ownedProvider && resolvedProvider != null) { + resolvedProvider.shutdown(); + } + resolvedProvider = null; + + File tmp = tempFlagFile; + tempFlagFile = null; + if (tmp != null) { + Files.deleteIfExists(tmp.toPath()); + } + + super.doStop(); + } + + @SuppressWarnings("unchecked") + MutableContext buildContext(Exchange exchange) { + MutableContext ctx = new MutableContext(); + + // 1. CamelOpenFeatureEvaluationContext header + Object contextHeader = exchange.getMessage().getHeader(OpenFeatureConstants.EVALUATION_CONTEXT); + if (contextHeader == null) { + contextHeader = exchange.getProperty(OpenFeatureConstants.EVALUATION_CONTEXT); + } + if (contextHeader instanceof Map) { + addMapToContext(ctx, (Map<String, Object>) contextHeader); + } else { + // Fallback to body map entries + Object body = exchange.getMessage().getBody(); + if (body instanceof Map) { + addMapToContext(ctx, (Map<String, Object>) body); + } + } + + // 2. CamelOpenFeatureTargetingKey header or exchange property + String targetingKey = exchange.getMessage().getHeader(OpenFeatureConstants.TARGETING_KEY, String.class); + if (targetingKey == null) { + targetingKey = exchange.getProperty(OpenFeatureConstants.TARGETING_KEY, String.class); + } + if (targetingKey != null) { + ctx.setTargetingKey(targetingKey); + } + + return ctx; + } + + private static void addMapToContext(MutableContext ctx, Map<String, Object> map) { + for (Map.Entry<String, Object> entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue() != null ? String.valueOf(entry.getValue()) : ""; Review Comment: Fixed. Added a `toValue(Object)` method that preserves typed values — Boolean, String, Integer, Long, Double, Instant are mapped to their corresponding `Value` constructors. Falls back to `String.valueOf` only for unsupported types. Context is now built with `new MutableContext(targetingKey, Map<String, Value>)`. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,295 @@ +/* + * 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 + * + * http://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.apache.camel.component.openfeature; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Map; + +import dev.openfeature.contrib.providers.flagd.Config; +import dev.openfeature.contrib.providers.flagd.FlagdOptions; +import dev.openfeature.contrib.providers.flagd.FlagdProvider; +import dev.openfeature.sdk.Client; +import dev.openfeature.sdk.FeatureProvider; +import dev.openfeature.sdk.MutableContext; +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; +import org.apache.camel.support.ResourceHelper; + +/** Evaluate feature flags using the OpenFeature specification with flagd. */ +@UriEndpoint(firstVersion = "4.23.0", scheme = "openfeature", title = "OpenFeature", syntax = "openfeature:domain", + producerOnly = true, category = { Category.CORE }) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final String DEFAULT_PROVIDER_BEAN = "flags"; + + @UriPath + @Metadata(required = true) + private String domain; + + @UriParam + private OpenFeatureConfiguration configuration; + + private volatile Client client; + private volatile FeatureProvider resolvedProvider; + private volatile File tempFlagFile; + private volatile boolean ownedProvider; + + public OpenFeatureEndpoint(String uri, OpenFeatureComponent component, String domain, + OpenFeatureConfiguration configuration) { + super(uri, component); + this.domain = domain; + this.configuration = configuration; + } + + @Override + public OpenFeatureComponent getComponent() { + return (OpenFeatureComponent) super.getComponent(); + } + + @Override + public Producer createProducer() { + return new OpenFeatureProducer(this); + } + + @Override + public Consumer createConsumer(Processor processor) { + throw new UnsupportedOperationException("OpenFeature is producer only"); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + configuration.validate(); + + if (domain == null || domain.isBlank()) { + throw new IllegalArgumentException("domain must not be blank"); + } + + FeatureProvider provider = resolveProvider(); Review Comment: Fixed. The component now tracks providers per domain via a `DomainBinding` inner class with reference counting. `registerEndpoint(domain, provider, owned)` logs a WARN when an endpoint's provider settings differ from the already-bound one, shuts down the unused owned provider, and reuses the existing binding. No more one-provider-per-endpoint fan-out. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java: ########## @@ -0,0 +1,79 @@ +/* + * 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 + * + * http://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.apache.camel.component.openfeature; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import dev.openfeature.sdk.Client; +import dev.openfeature.sdk.FeatureProvider; +import dev.openfeature.sdk.OpenFeatureAPI; +import org.apache.camel.Endpoint; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.DefaultComponent; + +@Component("openfeature") +public class OpenFeatureComponent extends DefaultComponent { + + @Metadata + private OpenFeatureConfiguration configuration = new OpenFeatureConfiguration(); + + private volatile OpenFeatureAPI api; + private final Set<String> initializedDomains = ConcurrentHashMap.newKeySet(); + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { + OpenFeatureEndpoint endpoint = new OpenFeatureEndpoint(uri, this, remaining, configuration.copy()); + setProperties(endpoint, parameters); + return endpoint; + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + api = OpenFeatureAPI.createIsolated(); + } + + @Override + protected void doStop() throws Exception { + OpenFeatureAPI a = api; + api = null; + initializedDomains.clear(); + if (a != null) { + a.shutdown(); + } + super.doStop(); + } + + synchronized Client registerProviderAndGetClient(String domain, FeatureProvider provider) throws Exception { + if (initializedDomains.add(domain)) { Review Comment: Fixed. `DomainBinding` tracks a `refCount` per domain. `unregisterEndpoint(domain)` decrements it; when the count reaches zero, the owned provider is shut down and unbound from the API. `doStop()` iterates over remaining bindings and shuts down only owned providers individually, rather than calling `api.shutdown()` which would affect unowned beans. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
