christophd commented on code in PR #27440:
URL: https://github.com/apache/camel/pull/27440#discussion_r4198608912


##########
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();

Review Comment:
   Fixed. `doStop()` no longer calls `api.shutdown()`. Instead it iterates over 
the `DomainBinding` map and only shuts down providers that are `owned` (created 
by the component). Providers passed via `provider=#bean` or from the registry 
are left untouched.



##########
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()) {
+            return false;
+        }
+
+        return "true".equalsIgnoreCase(defaultValue) || 
"false".equalsIgnoreCase(defaultValue);
+    }
+
+    public OpenFeatureConfiguration copy() {
+        try {
+            return (OpenFeatureConfiguration) clone();
+        } catch (CloneNotSupportedException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    void validate() {
+        if (provider != null && (flags != null || flagsResource != null)) {

Review Comment:
   Fixed. Removed the mutual exclusion check. When `provider` is set, it now 
takes precedence over `flags`/`flagsResource`/`host` — inherited 
component-level flagd settings no longer block an endpoint-level provider bean. 
Updated the provider description to document this: "When set, takes precedence 
over flags, flagsResource, and host".



##########
parent/pom.xml:
##########
@@ -418,7 +418,9 @@
         <ognl-version>3.4.14</ognl-version>
         <opa-version>2.1.1</opa-version>
         <opa-wasm-version>1.1.0</opa-wasm-version>
+        <openfeature-sdk-version>1.22.1</openfeature-sdk-version>
         <openfga-version>0.11.0</openfga-version>
+        <flagd-provider-version>0.14.2</flagd-provider-version>

Review Comment:
   Fixed. Added version properties `flagd-core-version` (2.0.1) and 
`flagd-api-version` (1.0.0) in `parent/pom.xml` with `dependencyManagement` 
entries to pin the open-range transitive dependencies from flagd.



##########
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()) : "";
+            if ("targetingKey".equals(key)) {
+                ctx.setTargetingKey(value);
+            } else {
+                ctx.add(key, value);
+            }
+        }
+    }
+
+    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;
+    }
+
+    public Object evaluate(Exchange exchange) {
+        Client c = client;
+        if (c == null) {
+            throw new IllegalStateException("OpenFeature endpoint is not 
started");
+        }
+        String flagKey = resolveFlagKey(exchange);
+        MutableContext ctx = buildContext(exchange);
+
+        if (configuration.isBooleanEvaluation(exchange, ctx)) {
+            boolean defaultVal = 
Boolean.parseBoolean(configuration.getDefaultValue());
+            return c.getBooleanValue(flagKey, defaultVal, ctx);
+        } else {
+            return c.getStringValue(flagKey, configuration.getDefaultValue(), 
ctx);
+        }
+    }
+
+    private FeatureProvider resolveProvider() throws IOException {
+        // 1. Explicit provider bean reference
+        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);
+            }
+            ownedProvider = false;
+            return provider;
+        }
+
+        // 2. Registry lookup for default bean
+        FeatureProvider defaultProvider = getCamelContext().getRegistry()
+                .lookupByNameAndType(DEFAULT_PROVIDER_BEAN, 
FeatureProvider.class);
+        if (defaultProvider != null) {
+            ownedProvider = false;
+            return defaultProvider;
+        }
+
+        // 3. Fallback to FlagdProvider
+        ownedProvider = true;
+        return createFlagdProvider();
+    }
+
+    private FeatureProvider createFlagdProvider() throws IOException {
+        if (configuration.getFlags() != null) {
+            return createFileProvider(configuration.getFlags());
+        }
+        if (configuration.getFlagsResource() != null) {
+            String content = loadResource(configuration.getFlagsResource());
+            return createFileProvider(content);
+        }
+        if (configuration.getHost() != null) {
+            FlagdOptions options = FlagdOptions.builder()

Review Comment:
   Fixed. Added `tls` (boolean, default false), `certPath` (String), and 
`deadline` (int, default 500ms) endpoint options. The remote flagd builder now 
uses these when building `FlagdOptions`. Updated the component documentation 
with a "Remote flagd service with TLS" section showing configuration examples.



-- 
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]

Reply via email to