gnodet-bot commented on code in PR #27440:
URL: https://github.com/apache/camel/pull/27440#discussion_r4223542543


##########
components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java:
##########
@@ -0,0 +1,215 @@
+/*
+ * 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.nio.file.Files;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+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 final ConcurrentHashMap<String, Object> domainLocks = new 
ConcurrentHashMap<>();
+
+    private static class DomainBinding {
+        final FeatureProvider provider;
+        final boolean owned;
+        int refCount;
+        File tempFlagFile;
+        private final AtomicBoolean shutdownCalled = new AtomicBoolean();
+
+        DomainBinding(FeatureProvider provider, boolean owned) {
+            this.provider = provider;
+            this.owned = owned;
+            this.refCount = 1;
+        }
+
+        void shutdown() {
+            if (!shutdownCalled.compareAndSet(false, true)) {
+                return;
+            }
+            if (owned) {
+                try {
+                    provider.shutdown();
+                } catch (Exception e) {
+                    LOG.debug("Error shutting down owned provider: {}", 
e.getMessage(), e);
+                }
+            }
+
+            if (tempFlagFile != null) {
+                try {
+                    Files.deleteIfExists(tempFlagFile.toPath());
+                } catch (IOException e) {
+                    LOG.debug("Error deleting temp flag file: {}", 
e.getMessage(), e);
+                }
+                tempFlagFile = null;
+            }
+        }
+    }
+
+    static class ProviderRegistration {
+        final FeatureProvider provider;
+        final boolean owned;
+        File tempFlagFile;
+
+        ProviderRegistration(FeatureProvider provider, boolean owned) {
+            this.provider = provider;
+            this.owned = owned;
+        }
+    }
+
+    @FunctionalInterface
+    interface ProviderSupplier {
+        ProviderRegistration get() throws Exception;
+    }
+
+    @Override
+    protected Endpoint createEndpoint(String uri, String remaining, 
Map<String, Object> parameters) throws Exception {
+        String domain = remaining;
+        String evaluationType = null;
+        int idx = remaining.indexOf('/');
+        if (idx >= 0) {
+            domain = remaining.substring(0, idx);
+            String pathValue = remaining.substring(idx + 1);
+            if (!pathValue.isBlank()) {
+                evaluationType = pathValue;
+            }
+        }
+        OpenFeatureEndpoint endpoint = new OpenFeatureEndpoint(uri, this, 
domain, evaluationType, configuration.copy());
+        setProperties(endpoint, parameters);
+        return endpoint;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        super.doStart();
+        api = OpenFeatureAPI.createIsolated();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (api == null) {
+            return;
+        }
+
+        OpenFeatureAPI localApi = api;
+        api = null;
+
+        for (Map.Entry<String, DomainBinding> bindingEntry : 
domainBindings.entrySet()) {
+            Object lock = domainLocks.computeIfAbsent(bindingEntry.getKey(), k 
-> new Object());
+            synchronized (lock) {
+                bindingEntry.getValue().shutdown();
+            }
+        }
+        domainBindings.clear();
+        domainLocks.clear();
+        try {
+            localApi.shutdown();
+        } catch (Exception e) {
+            LOG.debug("Error shutting down OpenFeature API: {}", 
e.getMessage(), e);
+        }
+        super.doStop();
+    }
+
+    Client acquireOrRegister(String domain, ProviderSupplier providerSupplier) 
throws Exception {
+        if (api == null) {
+            throw new IllegalStateException("OpenFeature component is not 
started");
+        }
+
+        Object lock = domainLocks.computeIfAbsent(domain, k -> new Object());
+        synchronized (lock) {
+            OpenFeatureAPI localApi = api;
+            if (localApi == null) {
+                throw new IllegalStateException("OpenFeature component is 
stopping or has been stopped");
+            }
+
+            DomainBinding existing = domainBindings.get(domain);
+            if (existing != null) {
+                existing.refCount++;
+                return localApi.getClient(domain);
+            }
+
+            ProviderRegistration reg = providerSupplier.get();
+            try {
+                localApi.setProviderAndWait(domain, reg.provider);
+            } catch (Exception e) {
+                if (reg.owned) {
+                    try {
+                        reg.provider.shutdown();
+                    } catch (Exception suppressed) {
+                        e.addSuppressed(suppressed);
+                    }
+                }
+                if (reg.tempFlagFile != null) {
+                    try {
+                        Files.deleteIfExists(reg.tempFlagFile.toPath());
+                    } catch (IOException suppressed) {
+                        e.addSuppressed(suppressed);
+                    }
+                }
+                throw e;
+            }
+            DomainBinding binding = new DomainBinding(reg.provider, reg.owned);
+            binding.tempFlagFile = reg.tempFlagFile;
+            domainBindings.put(domain, binding);
+            return localApi.getClient(domain);
+        }
+    }
+
+    void unregisterEndpoint(String domain) {

Review Comment:
   🐛 **`domainLocks` entries accumulate indefinitely (thread 
`PRRT_kwDOAAMl7c6qd-Oc`)**
   
   The author's explanation says `domainLocks.remove(domain)` was intentionally 
removed to avoid a split-lock race (a concurrent `computeIfAbsent` getting a 
new lock object). This concern is valid, but the chosen fix trades one 
correctness issue for a memory leak: every domain that has ever been used and 
deregistered leaves a dead `Object` in `domainLocks` forever (until the 
component stops).
   
   The safe fix is to remove the lock entry **after `binding.shutdown()` 
completes, while still inside `synchronized(lock)`**:
   
   ```suggestion
                       domainBindings.remove(domain);
                       binding.shutdown();
                       domainLocks.remove(domain);
   ```
   
   This is safe because:
   - The lock is still held when `remove` runs — no other thread can 
`computeIfAbsent` a new lock for this domain until after `synchronized(lock)` 
exits.
   - Once `remove` is called and the block exits, any concurrent 
`computeIfAbsent` will insert a fresh lock — correct behavior for a 
re-registration after the last endpoint deregistered.
   - `binding.shutdown()` is idempotent (guarded by `AtomicBoolean`), so a 
concurrent `doStop()` calling it causes no double-shutdown.



##########
components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java:
##########
@@ -0,0 +1,215 @@
+/*
+ * 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.nio.file.Files;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+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 final ConcurrentHashMap<String, Object> domainLocks = new 
ConcurrentHashMap<>();
+
+    private static class DomainBinding {
+        final FeatureProvider provider;
+        final boolean owned;
+        int refCount;
+        File tempFlagFile;
+        private final AtomicBoolean shutdownCalled = new AtomicBoolean();
+
+        DomainBinding(FeatureProvider provider, boolean owned) {
+            this.provider = provider;
+            this.owned = owned;
+            this.refCount = 1;
+        }
+
+        void shutdown() {
+            if (!shutdownCalled.compareAndSet(false, true)) {
+                return;
+            }
+            if (owned) {
+                try {
+                    provider.shutdown();
+                } catch (Exception e) {
+                    LOG.debug("Error shutting down owned provider: {}", 
e.getMessage(), e);
+                }
+            }
+
+            if (tempFlagFile != null) {
+                try {
+                    Files.deleteIfExists(tempFlagFile.toPath());
+                } catch (IOException e) {
+                    LOG.debug("Error deleting temp flag file: {}", 
e.getMessage(), e);
+                }
+                tempFlagFile = null;
+            }
+        }
+    }
+
+    static class ProviderRegistration {
+        final FeatureProvider provider;
+        final boolean owned;
+        File tempFlagFile;
+
+        ProviderRegistration(FeatureProvider provider, boolean owned) {
+            this.provider = provider;
+            this.owned = owned;
+        }
+    }
+
+    @FunctionalInterface
+    interface ProviderSupplier {
+        ProviderRegistration get() throws Exception;
+    }
+
+    @Override
+    protected Endpoint createEndpoint(String uri, String remaining, 
Map<String, Object> parameters) throws Exception {
+        String domain = remaining;
+        String evaluationType = null;
+        int idx = remaining.indexOf('/');
+        if (idx >= 0) {
+            domain = remaining.substring(0, idx);
+            String pathValue = remaining.substring(idx + 1);
+            if (!pathValue.isBlank()) {
+                evaluationType = pathValue;
+            }
+        }
+        OpenFeatureEndpoint endpoint = new OpenFeatureEndpoint(uri, this, 
domain, evaluationType, configuration.copy());
+        setProperties(endpoint, parameters);
+        return endpoint;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        super.doStart();
+        api = OpenFeatureAPI.createIsolated();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (api == null) {
+            return;
+        }
+
+        OpenFeatureAPI localApi = api;
+        api = null;
+
+        for (Map.Entry<String, DomainBinding> bindingEntry : 
domainBindings.entrySet()) {
+            Object lock = domainLocks.computeIfAbsent(bindingEntry.getKey(), k 
-> new Object());
+            synchronized (lock) {
+                bindingEntry.getValue().shutdown();
+            }
+        }
+        domainBindings.clear();
+        domainLocks.clear();
+        try {
+            localApi.shutdown();
+        } catch (Exception e) {
+            LOG.debug("Error shutting down OpenFeature API: {}", 
e.getMessage(), e);
+        }
+        super.doStop();
+    }
+
+    Client acquireOrRegister(String domain, ProviderSupplier providerSupplier) 
throws Exception {
+        if (api == null) {
+            throw new IllegalStateException("OpenFeature component is not 
started");
+        }
+
+        Object lock = domainLocks.computeIfAbsent(domain, k -> new Object());
+        synchronized (lock) {
+            OpenFeatureAPI localApi = api;
+            if (localApi == null) {

Review Comment:
   ⚠️ **Residual TOCTOU race with `doStop()` (thread `PRRT_kwDOAAMl7c6qd-Ox`)**
   
   The NPE path is now fixed (null check inside `synchronized(lock)` at line 
156). However, there is a residual race where `doStop()` can run to completion 
**after** `localApi` is captured as non-null here, but **before** 
`setProviderAndWait()` is called below.
   
   Concrete scenario:
   1. `acquireOrRegister` acquires `lock`, captures `localApi = api` 
(non-null), passes the null check.
   2. `doStop()` runs: sets `api = null`, iterates bindings (domain not 
registered yet), clears `domainBindings`, clears `domainLocks`, **calls 
`localApi.shutdown()`**.
   3. `acquireOrRegister` resumes, calls `localApi.setProviderAndWait(domain, 
provider)` — on an already-shut-down API.
   
   If the OpenFeature SDK's `setProviderAndWait` does not throw on a shut-down 
API, the `FlagdProvider` (gRPC channel, temp file) is registered to a defunct 
API instance and is never cleaned up.
   
   Adding `!isStarted()` to the guard closes the window cleanly — 
`DefaultComponent.isStarted()` is thread-safe:
   
   ```suggestion
               OpenFeatureAPI localApi = api;
               if (localApi == null || !isStarted()) {
   ```



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