gnodet-bot commented on code in PR #27440: URL: https://github.com/apache/camel/pull/27440#discussion_r4207470284
########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,435 @@ +/* + * 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.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.FlagEvaluationDetails; +import dev.openfeature.sdk.MutableContext; +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.Value; +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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** 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.CLOUD }, headersClass = OpenFeatureConstants.class) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final Logger LOG = LoggerFactory.getLogger(OpenFeatureEndpoint.class); + 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 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"); + } + + if (getComponent().hasDomainBinding(domain)) { + client = getComponent().acquireClient(domain); + } else { + FeatureProvider provider = resolveProvider(); + client = getComponent().registerEndpoint(domain, provider, ownedProvider); + } + } Review Comment: ⚠️ **TOCTOU race — not atomic across two separate locks** `hasDomainBinding()` (line 103) and `registerEndpoint()` (line 109) are each individually `synchronized`, but the check-then-act is not atomic. Two endpoints starting concurrently on the same domain can both see `hasDomainBinding == false`, both call `resolveProvider()`, and both call `registerEndpoint()` — the second clobbers the first provider binding. Fix: add a combined `acquireOrRegister(domain, Callable<FeatureProvider>)` method on the component that holds the lock for the entire check-resolve-register sequence. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,435 @@ +/* + * 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.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.FlagEvaluationDetails; +import dev.openfeature.sdk.MutableContext; +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.Value; +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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** 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.CLOUD }, headersClass = OpenFeatureConstants.class) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final Logger LOG = LoggerFactory.getLogger(OpenFeatureEndpoint.class); + 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 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"); + } + + if (getComponent().hasDomainBinding(domain)) { + client = getComponent().acquireClient(domain); + } else { + FeatureProvider provider = resolveProvider(); + client = getComponent().registerEndpoint(domain, provider, ownedProvider); + } + } + + @Override + protected void doStop() throws Exception { + if (client != null) { + client = null; + getComponent().unregisterEndpoint(domain); + } + ownedProvider = false; + + File tmp = tempFlagFile; + tempFlagFile = null; + if (tmp != null) { + Files.deleteIfExists(tmp.toPath()); + } + + super.doStop(); + } + + /** + * Evaluate a flag from the producer path. Reads flag key, evaluation type, targeting key and context from exchange + * headers/properties/configuration. Sets result detail headers on the exchange. + */ + public Object evaluate(Exchange exchange) { + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); Review Comment: ⚠️ **Temp flag file deleted while shared provider may still use it** When multiple endpoints share a domain (second endpoint calls `acquireClient`), the FlagdProvider FILE resolver on the shared provider still watches this temp file. The first endpoint to stop will delete the file from under a still-running provider. The temp file should only be deleted when the underlying FlagdProvider is actually shut down — i.e. when `unregisterEndpoint` drops the ref count to zero and calls `binding.provider.shutdown()`. Consider moving `tempFlagFile` ownership to the component's `DomainBinding` so cleanup is tied to provider lifecycle. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,435 @@ +/* + * 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.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.FlagEvaluationDetails; +import dev.openfeature.sdk.MutableContext; +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.Value; +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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** 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.CLOUD }, headersClass = OpenFeatureConstants.class) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final Logger LOG = LoggerFactory.getLogger(OpenFeatureEndpoint.class); + 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 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"); + } + + if (getComponent().hasDomainBinding(domain)) { + client = getComponent().acquireClient(domain); + } else { + FeatureProvider provider = resolveProvider(); + client = getComponent().registerEndpoint(domain, provider, ownedProvider); + } + } + + @Override + protected void doStop() throws Exception { + if (client != null) { + client = null; + getComponent().unregisterEndpoint(domain); + } + ownedProvider = false; + + File tmp = tempFlagFile; + tempFlagFile = null; + if (tmp != null) { + Files.deleteIfExists(tmp.toPath()); + } + + super.doStop(); + } + + /** + * Evaluate a flag from the producer path. Reads flag key, evaluation type, targeting key and context from exchange + * headers/properties/configuration. Sets result detail headers on the exchange. + */ + public Object evaluate(Exchange exchange) { + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); + MutableContext ctx = buildContext(exchange); + FlagEvaluationDetails<?> details = evaluateDetails(flagKey, evalType, ctx); + setResultHeaders(exchange, details); + return details.getValue(); + } + + /** + * Evaluate a flag from the language path with explicit parameters. Does not read from or write to the exchange — no + * side effects on headers or properties. + */ + public Object evaluate(String flagKey, String evaluationType, String targetingKey, Map<String, Object> contextMap) { + MutableContext ctx = buildMutableContext(targetingKey, contextMap); + return evaluateDetails(flagKey, evaluationType, ctx).getValue(); + } + + private FlagEvaluationDetails<?> evaluateDetails(String flagKey, String evaluationType, MutableContext ctx) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + + FlagEvaluationDetails<?> details; + if (isBooleanEvaluation(evaluationType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + details = c.getBooleanDetails(flagKey, defaultVal, ctx); + } else { + details = c.getStringDetails(flagKey, configuration.getDefaultValue(), ctx); + } + + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + return details; + } + + @SuppressWarnings("unchecked") + MutableContext buildContext(Exchange exchange) { + Map<String, Object> contextMap = null; + + Object contextHeader = exchange.getMessage().getHeader(OpenFeatureConstants.EVALUATION_CONTEXT); + if (contextHeader == null) { + contextHeader = exchange.getProperty(OpenFeatureConstants.EVALUATION_CONTEXT); + } + if (contextHeader instanceof Map) { + contextMap = (Map<String, Object>) contextHeader; + } else if (configuration.isContextFromBody()) { + Object body = exchange.getMessage().getBody(); + if (body instanceof Map) { + contextMap = (Map<String, Object>) body; + } + } + + String targetingKey = exchange.getMessage().getHeader(OpenFeatureConstants.TARGETING_KEY, String.class); + if (targetingKey == null) { + targetingKey = exchange.getProperty(OpenFeatureConstants.TARGETING_KEY, String.class); + } + + return buildMutableContext(targetingKey, contextMap); + } + + static MutableContext buildMutableContext(String targetingKey, Map<String, Object> contextMap) { + if (contextMap == null || contextMap.isEmpty()) { + if (targetingKey != null) { + return new MutableContext(targetingKey); + } + return new MutableContext(); + } + + Map<String, Value> attributes = new HashMap<>(); + String tk = targetingKey; + for (Map.Entry<String, Object> entry : contextMap.entrySet()) { + if ("targetingKey".equals(entry.getKey())) { + if (tk == null && entry.getValue() != null) { + tk = String.valueOf(entry.getValue()); + } + } else { + attributes.put(entry.getKey(), toValue(entry.getValue())); + } + } + + if (tk != null) { + return new MutableContext(tk, attributes); + } + return new MutableContext(attributes); + } + + @SuppressWarnings("unchecked") + private static Value toValue(Object obj) { + if (obj == null) { + return new Value(); + } + if (obj instanceof Boolean) { + return new Value((Boolean) obj); + } + if (obj instanceof String) { + return new Value((String) obj); + } + if (obj instanceof Integer) { + return new Value((Integer) obj); + } + if (obj instanceof Long) { + return new Value((Long) obj); + } + if (obj instanceof Double) { + return new Value((Double) obj); + } + if (obj instanceof Number) { + return new Value(((Number) obj).doubleValue()); + } + if (obj instanceof Instant) { + return new Value((Instant) obj); + } + if (obj instanceof Map) { + Map<String, Value> attributes = new HashMap<>(); + for (Map.Entry<?, ?> entry : ((Map<?, ?>) obj).entrySet()) { + attributes.put(String.valueOf(entry.getKey()), toValue(entry.getValue())); + } + return new Value(new MutableStructure(attributes)); + } + if (obj instanceof List) { + List<Value> values = new ArrayList<>(); + for (Object item : (List<?>) obj) { + values.add(toValue(item)); + } + return new Value(values); + } + return new Value(String.valueOf(obj)); + } + + String resolveFlagKey(Exchange exchange) { + String key = exchange.getMessage().getHeader(OpenFeatureConstants.FLAG_KEY, String.class); + if (key == null) { + key = exchange.getProperty(OpenFeatureConstants.FLAG_KEY, String.class); + } + if (key == null) { + key = configuration.getFlagKey(); + } + if (key == null || key.isBlank()) { + throw new IllegalArgumentException( + "No flag key specified. Set flagKey on the endpoint or provide it via the " + + OpenFeatureConstants.FLAG_KEY + " header."); + } + return key; + } + + private String resolveEvaluationType(Exchange exchange) { + String evalType = exchange.getMessage().getHeader(OpenFeatureConstants.EVALUATION_TYPE, String.class); + if (evalType == null) { + evalType = exchange.getProperty(OpenFeatureConstants.EVALUATION_TYPE, String.class); + } + if (evalType == null) { + evalType = configuration.getEvaluationType(); + } + return evalType; + } + + private boolean isBooleanEvaluation(String evalType) { + if ("boolean".equalsIgnoreCase(evalType)) { + return true; + } + if ("variant".equalsIgnoreCase(evalType)) { + return false; + } + String dv = configuration.getDefaultValue(); + return "true".equalsIgnoreCase(dv) || "false".equalsIgnoreCase(dv); + } + + private void setResultHeaders(Exchange exchange, FlagEvaluationDetails<?> details) { + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_VARIANT); + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_REASON); + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_ERROR_CODE); + if (details.getVariant() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_VARIANT, details.getVariant()); + } + if (details.getReason() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_REASON, details.getReason()); + } + if (details.getErrorCode() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_ERROR_CODE, details.getErrorCode().name()); + } + } + Review Comment: 💡 **Silent implicit bean lookup — add a log message** If a bean named `"flags"` exists in the Camel registry it silently takes precedence over `flagsResource` and `host`, with no log output. A user who accidentally has a `"flags"` bean registered (from another component or test setup) will see their explicit config silently ignored. Consider adding at minimum: ```java LOG.debug("Using '{}' bean of type FeatureProvider found in Camel registry", DEFAULT_PROVIDER_BEAN); ``` ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,435 @@ +/* + * 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.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.FlagEvaluationDetails; +import dev.openfeature.sdk.MutableContext; +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.Value; +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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** 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.CLOUD }, headersClass = OpenFeatureConstants.class) +public class OpenFeatureEndpoint extends DefaultEndpoint { + + private static final Logger LOG = LoggerFactory.getLogger(OpenFeatureEndpoint.class); + 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 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"); + } + + if (getComponent().hasDomainBinding(domain)) { + client = getComponent().acquireClient(domain); + } else { + FeatureProvider provider = resolveProvider(); + client = getComponent().registerEndpoint(domain, provider, ownedProvider); + } + } + + @Override + protected void doStop() throws Exception { + if (client != null) { + client = null; + getComponent().unregisterEndpoint(domain); + } + ownedProvider = false; + + File tmp = tempFlagFile; + tempFlagFile = null; + if (tmp != null) { + Files.deleteIfExists(tmp.toPath()); + } + + super.doStop(); + } + + /** + * Evaluate a flag from the producer path. Reads flag key, evaluation type, targeting key and context from exchange + * headers/properties/configuration. Sets result detail headers on the exchange. + */ + public Object evaluate(Exchange exchange) { + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); + MutableContext ctx = buildContext(exchange); + FlagEvaluationDetails<?> details = evaluateDetails(flagKey, evalType, ctx); + setResultHeaders(exchange, details); + return details.getValue(); + } + + /** + * Evaluate a flag from the language path with explicit parameters. Does not read from or write to the exchange — no + * side effects on headers or properties. + */ + public Object evaluate(String flagKey, String evaluationType, String targetingKey, Map<String, Object> contextMap) { + MutableContext ctx = buildMutableContext(targetingKey, contextMap); + return evaluateDetails(flagKey, evaluationType, ctx).getValue(); + } + + private FlagEvaluationDetails<?> evaluateDetails(String flagKey, String evaluationType, MutableContext ctx) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + + FlagEvaluationDetails<?> details; + if (isBooleanEvaluation(evaluationType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + details = c.getBooleanDetails(flagKey, defaultVal, ctx); + } else { + details = c.getStringDetails(flagKey, configuration.getDefaultValue(), ctx); + } + + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + return details; + } + + @SuppressWarnings("unchecked") + MutableContext buildContext(Exchange exchange) { + Map<String, Object> contextMap = null; + + Object contextHeader = exchange.getMessage().getHeader(OpenFeatureConstants.EVALUATION_CONTEXT); + if (contextHeader == null) { + contextHeader = exchange.getProperty(OpenFeatureConstants.EVALUATION_CONTEXT); + } + if (contextHeader instanceof Map) { + contextMap = (Map<String, Object>) contextHeader; + } else if (configuration.isContextFromBody()) { + Object body = exchange.getMessage().getBody(); + if (body instanceof Map) { + contextMap = (Map<String, Object>) body; + } + } + + String targetingKey = exchange.getMessage().getHeader(OpenFeatureConstants.TARGETING_KEY, String.class); + if (targetingKey == null) { + targetingKey = exchange.getProperty(OpenFeatureConstants.TARGETING_KEY, String.class); + } + + return buildMutableContext(targetingKey, contextMap); + } + + static MutableContext buildMutableContext(String targetingKey, Map<String, Object> contextMap) { + if (contextMap == null || contextMap.isEmpty()) { + if (targetingKey != null) { + return new MutableContext(targetingKey); + } + return new MutableContext(); + } + + Map<String, Value> attributes = new HashMap<>(); + String tk = targetingKey; + for (Map.Entry<String, Object> entry : contextMap.entrySet()) { + if ("targetingKey".equals(entry.getKey())) { + if (tk == null && entry.getValue() != null) { + tk = String.valueOf(entry.getValue()); + } + } else { + attributes.put(entry.getKey(), toValue(entry.getValue())); + } + } + + if (tk != null) { + return new MutableContext(tk, attributes); + } + return new MutableContext(attributes); + } + + @SuppressWarnings("unchecked") + private static Value toValue(Object obj) { + if (obj == null) { + return new Value(); + } + if (obj instanceof Boolean) { + return new Value((Boolean) obj); + } + if (obj instanceof String) { + return new Value((String) obj); + } + if (obj instanceof Integer) { + return new Value((Integer) obj); + } + if (obj instanceof Long) { + return new Value((Long) obj); + } + if (obj instanceof Double) { + return new Value((Double) obj); + } + if (obj instanceof Number) { + return new Value(((Number) obj).doubleValue()); + } + if (obj instanceof Instant) { + return new Value((Instant) obj); + } + if (obj instanceof Map) { + Map<String, Value> attributes = new HashMap<>(); + for (Map.Entry<?, ?> entry : ((Map<?, ?>) obj).entrySet()) { + attributes.put(String.valueOf(entry.getKey()), toValue(entry.getValue())); + } + return new Value(new MutableStructure(attributes)); + } + if (obj instanceof List) { + List<Value> values = new ArrayList<>(); + for (Object item : (List<?>) obj) { + values.add(toValue(item)); + } + return new Value(values); + } + return new Value(String.valueOf(obj)); + } + + String resolveFlagKey(Exchange exchange) { + String key = exchange.getMessage().getHeader(OpenFeatureConstants.FLAG_KEY, String.class); + if (key == null) { + key = exchange.getProperty(OpenFeatureConstants.FLAG_KEY, String.class); + } + if (key == null) { + key = configuration.getFlagKey(); + } + if (key == null || key.isBlank()) { + throw new IllegalArgumentException( + "No flag key specified. Set flagKey on the endpoint or provide it via the " + + OpenFeatureConstants.FLAG_KEY + " header."); + } + return key; + } + + private String resolveEvaluationType(Exchange exchange) { + String evalType = exchange.getMessage().getHeader(OpenFeatureConstants.EVALUATION_TYPE, String.class); + if (evalType == null) { + evalType = exchange.getProperty(OpenFeatureConstants.EVALUATION_TYPE, String.class); + } + if (evalType == null) { + evalType = configuration.getEvaluationType(); + } + return evalType; + } + + private boolean isBooleanEvaluation(String evalType) { + if ("boolean".equalsIgnoreCase(evalType)) { + return true; + } + if ("variant".equalsIgnoreCase(evalType)) { + return false; + } + String dv = configuration.getDefaultValue(); + return "true".equalsIgnoreCase(dv) || "false".equalsIgnoreCase(dv); + } + + private void setResultHeaders(Exchange exchange, FlagEvaluationDetails<?> details) { + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_VARIANT); + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_REASON); + exchange.getMessage().removeHeader(OpenFeatureConstants.EVALUATION_ERROR_CODE); + if (details.getVariant() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_VARIANT, details.getVariant()); + } + if (details.getReason() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_REASON, details.getReason()); + } + if (details.getErrorCode() != null) { + exchange.getMessage().setHeader(OpenFeatureConstants.EVALUATION_ERROR_CODE, details.getErrorCode().name()); + } + } + + private FeatureProvider resolveProvider() throws IOException { + String providerRef = configuration.getProvider(); + if (providerRef != null) { + String beanName = providerRef.startsWith("#") ? providerRef.substring(1) : providerRef; + FeatureProvider provider = getCamelContext().getRegistry() + .lookupByNameAndType(beanName, FeatureProvider.class); + if (provider == null) { + throw new IllegalArgumentException( + "No FeatureProvider bean found in the registry with name: " + beanName); + } + return provider; + } + + FeatureProvider defaultProvider = getCamelContext().getRegistry() + .lookupByNameAndType(DEFAULT_PROVIDER_BEAN, FeatureProvider.class); + if (defaultProvider != null) { + return defaultProvider; + } + + return createFlagdProvider(); + } + + private FeatureProvider createFlagdProvider() throws IOException { + ownedProvider = true; + if (configuration.getFlags() != null) { + return createFileProviderFromContent(configuration.getFlags()); + } + if (configuration.getFlagsResource() != null) { + String resource = configuration.getFlagsResource(); + if (resource.startsWith("file:")) { + return createFileProviderFromPath(resource.substring(5)); + } + String content = loadResource(resource); + return createFileProviderFromContent(content); + } + if (configuration.getHost() != null) { + FlagdOptions.FlagdOptionsBuilder builder = FlagdOptions.builder() + .host(configuration.getHost()) + .port(configuration.getPort()) + .deadline(configuration.getDeadline()); + if (configuration.isTls()) { + builder.tls(true); + if (configuration.getCertPath() != null) { + builder.certPath(configuration.getCertPath()); + } + } Review Comment: 💡 **`certPath` silently ignored when `tls=false`** Setting `certPath` without enabling `tls=true` is a silent no-op. A user expecting mutual TLS who forgets `tls=true` will get an unencrypted connection with no warning. ```suggestion if (configuration.isTls()) { builder.tls(true); if (configuration.getCertPath() != null) { builder.certPath(configuration.getCertPath()); } } else if (configuration.getCertPath() != null) { LOG.warn("certPath is configured but tls=false; certPath will be ignored. Set tls=true to enable TLS."); } ``` ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureConfiguration.java: ########## @@ -0,0 +1,234 @@ +/* + * 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 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", defaultValue = "false", + description = "Whether to use TLS for the remote flagd connection.") + private boolean tls; + + @UriParam(label = "common", + description = "Path to the TLS certificate for the remote flagd connection.") + private String certPath; + + @UriParam(label = "common", defaultValue = "500", + description = "Deadline in milliseconds for the remote flagd connection.") + private int deadline = 500; Review Comment: 💡 **TLS parameters should use `label = "security"`, not `"common"`** Camel convention (followed by `camel-http`, `camel-netty`, and most remote components) is to label TLS-related parameters with `"security"` so they appear in the security section of generated documentation. Both `tls` and `certPath` should use `label = "security"`. -- 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]
