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


##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.opa;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.camel.CamelContext;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Atomically replaces validated WASM policy/data snapshots while admitted 
evaluations drain the previous snapshot.
+ * Resource loading and policy construction never hold the decision-state lock.
+ */
+public final class OpaReloadableWasmEvaluator extends OpaPolicyEvaluator 
implements AutoCloseable {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+    private static final Logger LOG = 
LoggerFactory.getLogger(OpaReloadableWasmEvaluator.class);
+
+    @FunctionalInterface
+    interface BundleLoader {
+        OpaWasmEvaluator.Bundle load() throws Exception;
+    }
+
+    @FunctionalInterface
+    interface EvaluatorFactory {
+        OpaWasmEvaluator create(OpaWasmEvaluator.Bundle bundle) throws 
Exception;
+    }
+
+    private final Object state = new Object();
+    private final Object reloadLock = new Object();
+    private final CamelContext camelContext;
+    private final long reloadInterval;
+    private final BundleLoader loader;
+    private final EvaluatorFactory factory;
+    private Snapshot active;
+    private boolean closed;
+    private boolean reloadEnabled = true;
+    private long watchGeneration;
+    /** The revision of content that failed to load; a poll does not rebuild 
it until the content changes. */
+    private String lastFailedRevision;
+    private ScheduledExecutorService executor;
+    private ScheduledFuture<?> watch;
+    private volatile OpaPolicyReloadStatus status;
+
+    OpaReloadableWasmEvaluator(CamelContext camelContext, long reloadInterval, 
BundleLoader loader,
+                               EvaluatorFactory factory, String policyPath, 
String allowKey, String includeHeaders,
+                               String includeProperties, boolean includeBody, 
boolean failOpen) throws Exception {
+        super(policyPath, allowKey, includeHeaders, includeProperties, 
includeBody, failOpen);
+        if (reloadInterval < 0) {
+            throw new IllegalArgumentException("policyReloadInterval must not 
be negative");
+        }
+        this.camelContext = ObjectHelper.notNull(camelContext, "camelContext");
+        this.reloadInterval = reloadInterval;
+        this.loader = loader;
+        this.factory = factory;
+        OpaWasmEvaluator.Bundle bundle = immutableBundle(loader.load());
+        String revision = revision(bundle);
+        // OpaWasmEvaluator warms its pool and applies the configured 
entrypoint/data before returning.
+        this.active = new Snapshot(factory.create(bundle), revision);
+        this.status = new OpaPolicyReloadStatus(revision, Instant.now(), null, 
null);
+    }
+
+    public static OpaReloadableWasmEvaluator create(
+            CamelContext camelContext, String policyBundle, String entrypoint, 
int poolSize, long borrowTimeout,
+            long reloadInterval, String policyPath, String allowKey, String 
includeHeaders, String includeProperties,
+            boolean includeBody, boolean failOpen)
+            throws Exception {
+        OpaWasmEvaluator.validateWasmOptions(policyBundle, poolSize);
+        String resolvedEntrypoint = ObjectHelper.isNotEmpty(entrypoint) ? 
entrypoint : policyPath;
+        return new OpaReloadableWasmEvaluator(
+                camelContext, reloadInterval,
+                () -> OpaWasmEvaluator.loadPolicy(camelContext, policyBundle),
+                bundle -> new OpaWasmEvaluator(
+                        bundle.wasm(), bundle.data(), resolvedEntrypoint, 
poolSize, borrowTimeout,
+                        policyPath, allowKey, includeHeaders, 
includeProperties, includeBody, failOpen),
+                policyPath, allowKey, includeHeaders, includeProperties, 
includeBody, failOpen);
+    }
+
+    public OpaPolicyReloadStatus getReloadStatus() {
+        return status;
+    }
+
+    /** Re-reads the configured resource and publishes a validated replacement 
only when its content changed. */
+    public boolean reload() throws Exception {
+        long generation;
+        synchronized (state) {
+            ensureOpen(-1);
+            if (!reloadEnabled) {
+                throw new IllegalStateException("The WASM policy reload 
watcher is stopped");
+            }
+            generation = watchGeneration;
+        }
+        // an explicit reload tries again even when the same content failed 
before
+        return reload(generation, false);
+    }
+
+    private boolean reload(long generation, boolean skipKnownFailure) throws 
Exception {
+        synchronized (reloadLock) {
+            synchronized (state) {
+                ensureOpen(generation);
+            }
+            OpaWasmEvaluator replacement = null;
+            boolean published = false;
+            String revision = null;
+            try {
+                OpaWasmEvaluator.Bundle loaded = loader.load();
+                // computed before the validation, so content that loads but 
does not validate is remembered too
+                revision = revision(loaded);
+                OpaWasmEvaluator.Bundle bundle = immutableBundle(loaded);
+                synchronized (state) {
+                    ensureOpen(generation);
+                    if (active.revision.equals(revision)) {
+                        // a successful check; the last failure stays visible 
in the status
+                        status = new OpaPolicyReloadStatus(
+                                revision, Instant.now(), 
status.getLastFailedReload(), status.getLastReloadFailureType());
+                        return false;
+                    }
+                    if (skipKnownFailure && 
revision.equals(lastFailedRevision)) {
+                        // the content that failed to load is still there: 
building it again would fail the same way
+                        // and log the same warning on every poll, so wait for 
it to change
+                        LOG.debug("WASM policy {} still has the content that 
failed to load; waiting for it to change",
+                                getPolicyPath());
+                        return false;
+                    }
+                }
+                replacement = factory.create(bundle);
+                Snapshot previous;
+                synchronized (state) {
+                    ensureOpen(generation);
+                    previous = active;
+                    active = new Snapshot(replacement, revision);
+                    published = true;
+                    previous.retired = true;
+                    lastFailedRevision = null;
+                    status = new OpaPolicyReloadStatus(
+                            revision, Instant.now(), 
status.getLastFailedReload(), status.getLastReloadFailureType());
+                    if (previous.readers != 0) {
+                        previous = null;
+                    }
+                }
+                if (previous != null) {
+                    previous.evaluator.close();
+                }
+                return true;
+            } catch (Exception e) {

Review Comment:
   ⚠️ **`catch (Exception e)` misses `Error` types** — this creates an 
asymmetry with `poll()`, which correctly catches `Throwable` (line 240). If 
`factory.create(bundle)` throws an `Error` (e.g. `LinkageError` or 
`NoClassDefFoundError` from a malformed WASM native library), this `catch` 
block is bypassed: `lastFailedRevision` is never set, `status` is never 
updated, and on the next poll `skipKnownFailure` finds `lastFailedRevision == 
null` and retries the same content — logging a WARN on every interval.
   
   Since the method declares `throws Exception`, the fix is a second catch 
block before `finally`:
   
   ```suggestion
               } catch (Error e) {
                   synchronized (state) {
                       if (!closed && (generation < 0 || generation == 
watchGeneration)) {
                           lastFailedRevision = revision;
                           status = new OpaPolicyReloadStatus(
                                   active.revision, 
status.getLastSuccessfulCheck(),
                                   Instant.now(), e.getClass().getName());
                       }
                   }
                   throw e;
               } catch (Exception e) {
   ```
   
   This keeps the method signature and mirrors what `poll()` already does for 
the escape path.



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