davsclaus commented on code in PR #27440: URL: https://github.com/apache/camel/pull/27440#discussion_r4203984406
########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,420 @@ +/* + * 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.HashMap; +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.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 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().registerEndpoint(domain, provider, ownedProvider); Review Comment: `resolveProvider()` runs before checking whether the domain already has a binding, so each extra `openfeature:flags?flagKey=...` endpoint (and the language's default `openfeature:flags`) builds a new provider (and a temp file), then logs `already has a registered provider` and shuts it down, even when all endpoints inherit the same component settings. Could it look up the binding first, and only warn when the endpoint's own provider settings differ? ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,420 @@ +/* + * 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.HashMap; +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.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 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().registerEndpoint(domain, provider, ownedProvider); + } + + @Override + protected void doStop() throws Exception { + client = null; + resolvedProvider = null; + + getComponent().unregisterEndpoint(domain); + + 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) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); + MutableContext ctx = buildContext(exchange); + + if (isBooleanEvaluation(evalType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + FlagEvaluationDetails<Boolean> details = c.getBooleanDetails(flagKey, defaultVal, ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + return details.getValue(); + } else { + FlagEvaluationDetails<String> details = c.getStringDetails(flagKey, configuration.getDefaultValue(), ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + 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( + Exchange exchange, String flagKey, String evaluationType, String targetingKey, Map<String, Object> contextMap) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + MutableContext ctx = buildMutableContext(targetingKey, contextMap); + + if (isBooleanEvaluation(evaluationType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + return c.getBooleanValue(flagKey, defaultVal, ctx); + } else { + return c.getStringValue(flagKey, configuration.getDefaultValue(), ctx); + } Review Comment: The language path uses `getBooleanValue`/`getStringValue` without details, so a typo in the flag key silently evaluates to the default (false) with no log. Could it use the details variant and log the error like the producer does? (`exchange` is also unused here.) ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java: ########## @@ -0,0 +1,127 @@ +/* + * 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.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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component("openfeature") +public class OpenFeatureComponent extends DefaultComponent { + + private static final Logger LOG = LoggerFactory.getLogger(OpenFeatureComponent.class); + + @Metadata + private OpenFeatureConfiguration configuration = new OpenFeatureConfiguration(); + + private volatile OpenFeatureAPI api; + private final Map<String, DomainBinding> domainBindings = new ConcurrentHashMap<>(); + + private static class DomainBinding { + final FeatureProvider provider; + final boolean owned; + int refCount; + + DomainBinding(FeatureProvider provider, boolean owned) { + this.provider = provider; + this.owned = owned; + this.refCount = 1; + } + } + + @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 { + api = null; + for (DomainBinding binding : domainBindings.values()) { + if (binding.owned) { + try { + binding.provider.shutdown(); + } catch (Exception e) { + LOG.debug("Error shutting down owned provider: {}", e.getMessage(), e); + } + } + } + domainBindings.clear(); + super.doStop(); + } + + synchronized Client registerEndpoint(String domain, FeatureProvider provider, boolean owned) throws Exception { + DomainBinding existing = domainBindings.get(domain); + if (existing != null) { + existing.refCount++; + if (existing.provider != provider) { + LOG.warn("Domain '{}' already has a registered provider; this endpoint's provider settings are ignored.", + domain); + if (owned) { + provider.shutdown(); + } + } + return api.getClient(domain); + } + api.setProviderAndWait(domain, provider); + domainBindings.put(domain, new DomainBinding(provider, owned)); + return api.getClient(domain); + } + + synchronized void unregisterEndpoint(String domain) { + DomainBinding binding = domainBindings.get(domain); + if (binding != null) { + binding.refCount--; + if (binding.refCount <= 0) { + domainBindings.remove(domain); + if (binding.owned) { + try { + binding.provider.shutdown(); + } catch (Exception e) { + LOG.debug("Error shutting down owned provider for domain '{}': {}", domain, e.getMessage(), e); + } + } Review Comment: The owned provider is shut down but stays bound to the domain in the `OpenFeatureAPI`, so after a route reload the SDK later replaces an already shut-down provider. Unbind it as well? ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,420 @@ +/* + * 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.HashMap; +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.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 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().registerEndpoint(domain, provider, ownedProvider); + } + + @Override + protected void doStop() throws Exception { + client = null; + resolvedProvider = null; + + getComponent().unregisterEndpoint(domain); + + 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) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); + MutableContext ctx = buildContext(exchange); + + if (isBooleanEvaluation(evalType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + FlagEvaluationDetails<Boolean> details = c.getBooleanDetails(flagKey, defaultVal, ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + return details.getValue(); + } else { + FlagEvaluationDetails<String> details = c.getStringDetails(flagKey, configuration.getDefaultValue(), ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + 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( + Exchange exchange, String flagKey, String evaluationType, String targetingKey, Map<String, Object> contextMap) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + MutableContext ctx = buildMutableContext(targetingKey, contextMap); + + if (isBooleanEvaluation(evaluationType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + return c.getBooleanValue(flagKey, defaultVal, ctx); + } else { + return c.getStringValue(flagKey, configuration.getDefaultValue(), ctx); + } + } + + @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); + } + + 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).intValue()); + } + if (obj instanceof Double) { + return new Value((Double) obj); + } + if (obj instanceof Instant) { + return new Value((Instant) obj); + } + 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) { + 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: The headers are only set when non-null, so after a failed evaluation a later successful one still carries the old `CamelOpenFeatureErrorCode`. Remove the three headers first, then set them. ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureEndpoint.java: ########## @@ -0,0 +1,420 @@ +/* + * 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.HashMap; +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.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 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().registerEndpoint(domain, provider, ownedProvider); + } + + @Override + protected void doStop() throws Exception { + client = null; + resolvedProvider = null; + + getComponent().unregisterEndpoint(domain); + + 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) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + String flagKey = resolveFlagKey(exchange); + String evalType = resolveEvaluationType(exchange); + MutableContext ctx = buildContext(exchange); + + if (isBooleanEvaluation(evalType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + FlagEvaluationDetails<Boolean> details = c.getBooleanDetails(flagKey, defaultVal, ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + return details.getValue(); + } else { + FlagEvaluationDetails<String> details = c.getStringDetails(flagKey, configuration.getDefaultValue(), ctx); + setResultHeaders(exchange, details); + if (details.getErrorCode() != null) { + LOG.warn("OpenFeature evaluation error for flag '{}': {} - {}", + flagKey, details.getErrorCode(), details.getErrorMessage()); + } + 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( + Exchange exchange, String flagKey, String evaluationType, String targetingKey, Map<String, Object> contextMap) { + Client c = client; + if (c == null) { + throw new IllegalStateException("OpenFeature endpoint is not started"); + } + MutableContext ctx = buildMutableContext(targetingKey, contextMap); + + if (isBooleanEvaluation(evaluationType)) { + boolean defaultVal = Boolean.parseBoolean(configuration.getDefaultValue()); + return c.getBooleanValue(flagKey, defaultVal, ctx); + } else { + return c.getStringValue(flagKey, configuration.getDefaultValue(), ctx); + } + } + + @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); + } + + 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).intValue()); Review Comment: `intValue()` silently truncates longs outside the int range. Maybe `new Value(((Long) obj).doubleValue())` or a range check; also Float/Short/BigDecimal fall through to `String.valueOf` below, which breaks numeric comparisons in JsonLogic. -- 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]
