gnodet-bot commented on code in PR #27440: URL: https://github.com/apache/camel/pull/27440#discussion_r4217107517
########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java: ########## @@ -0,0 +1,200 @@ +/* + * 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 { + OpenFeatureAPI localApi = api; + api = null; Review Comment: ⚠️ **Concurrency bug: `doStop()` can null `api` while `acquireOrRegister` holds a per-domain lock** `doStop()` sets `api = null` (line 126) without acquiring any per-domain lock. Meanwhile, `acquireOrRegister` reads `api` at lines 147, 152, and 173 — all inside `synchronized(lock)` on a per-domain lock that `doStop()` never contends on. If `doStop()` runs concurrently with `acquireOrRegister`, the following can happen: 1. `acquireOrRegister` passes the `domainBindings.get(domain)` check (line 144), enters the registration path. 2. `doStop()` sets `api = null` and clears `domainBindings`. 3. `acquireOrRegister` calls `api.setProviderAndWait(...)` or `api.getClient(...)` → **NullPointerException**. `volatile` only guarantees visibility, not atomicity of the read-use pair across the `doStop()` write. Consider checking that the component is still running inside the lock before using `api`: ```suggestion synchronized (lock) { if (!isStarted()) { throw new IllegalStateException("OpenFeatureComponent is stopped"); } DomainBinding existing = domainBindings.get(domain); ``` Or use a `ReentrantReadWriteLock` to coordinate `doStop()` (write lock) with `acquireOrRegister`/`unregisterEndpoint` (read lock). ########## components/camel-openfeature/src/main/java/org/apache/camel/component/openfeature/OpenFeatureComponent.java: ########## @@ -0,0 +1,200 @@ +/* + * 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 { + OpenFeatureAPI localApi = api; + api = null; + for (DomainBinding binding : domainBindings.values()) { + binding.shutdown(); + } + domainBindings.clear(); + if (localApi != null) { + 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 { + Object lock = domainLocks.computeIfAbsent(domain, k -> new Object()); + synchronized (lock) { + DomainBinding existing = domainBindings.get(domain); + if (existing != null) { + existing.refCount++; + return api.getClient(domain); + } + + ProviderRegistration reg = providerSupplier.get(); + try { + api.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 api.getClient(domain); + } + } + + void unregisterEndpoint(String domain) { + Object lock = domainLocks.computeIfAbsent(domain, k -> new Object()); + synchronized (lock) { + DomainBinding binding = domainBindings.get(domain); + if (binding != null) { + binding.refCount--; + if (binding.refCount <= 0) { + domainBindings.remove(domain); + binding.shutdown(); + domainLocks.remove(domain); Review Comment: ⚠️ **Concurrency bug: `domainLocks.remove` while lock is held can split two threads onto different monitors** Removing the domain's lock from `domainLocks` while still holding it creates a window where a concurrent thread can `computeIfAbsent` a **new** lock object for the same domain — then both threads operate on different monitors simultaneously, defeating the purpose of per-domain locking. Scenario: 1. Thread B (`unregisterEndpoint`) acquires `lockA`, sees `refCount <= 0`, calls `domainLocks.remove(domain)` — `lockA` is now gone from the map, but thread B still holds it. 2. Thread A (`acquireOrRegister`) calls `computeIfAbsent` before the remove → it already has `lockA` and is blocked on B. This case is safe. 3. Thread C (`acquireOrRegister`) calls `computeIfAbsent` **after** B's remove → a new `lockC` is inserted and acquired. Threads A and C now each hold their own monitors for the same domain and run concurrently. Fix: don't remove the lock entry while holding it. Use a two-phase approach — after releasing the lock, attempt a conditional remove (only if the value in the map is still the same object): ```suggestion domainBindings.remove(domain); binding.shutdown(); } } } // Remove the lock entry only after releasing it, so no other thread can // computeIfAbsent a new lock for the same domain while we still hold this one. if (binding != null && binding.refCount <= 0) { domainLocks.remove(domain, lock); ``` Or, alternatively, never remove lock entries from `domainLocks` at all (they are lightweight `Object` instances) — this is the simpler fix. -- 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]
