oscerd commented on code in PR #29831:
URL: https://github.com/apache/camel/pull/29831#discussion_r4588764290


##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaReloadableWasmEvaluator.java:
##########
@@ -0,0 +1,330 @@
+/*
+ * 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 bundle = 
immutableBundle(loader.load());
+                revision = revision(bundle);

Review Comment:
   Fixed in (4050b4d059fa): the revision is computed from the loaded bundle 
before the validation, so a validation failure is remembered; a load failure is 
retried on every poll, which the doc now says. A watcher test counts the 
factory calls.
   
   _Claude Code on behalf of oscerd_



##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/security/OpaSecurityPolicy.java:
##########
@@ -457,6 +469,29 @@ public void setPoolSize(int poolSize) {
         this.poolSize = poolSize;
     }
 
+    public long getPolicyReloadInterval() {
+        return policyReloadInterval;
+    }
+
+    public void setPolicyReloadInterval(long policyReloadInterval) {
+        this.policyReloadInterval = policyReloadInterval;
+    }
+
+    public boolean reloadPolicy() throws Exception {

Review Comment:
   Added in (4050b4d059fa).
   
   _Claude Code on behalf of oscerd_



##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/security/OpaSecurityPolicy.java:
##########
@@ -457,6 +469,29 @@ public void setPoolSize(int poolSize) {
         this.poolSize = poolSize;
     }
 
+    public long getPolicyReloadInterval() {
+        return policyReloadInterval;
+    }
+
+    public void setPolicyReloadInterval(long policyReloadInterval) {
+        this.policyReloadInterval = policyReloadInterval;
+    }
+
+    public boolean reloadPolicy() throws Exception {
+        OpaReloadableWasmEvaluator wasm;
+        synchronized (this) {
+            if (activeProcessors == 0 || !(evaluator instanceof 
OpaReloadableWasmEvaluator)) {
+                throw new IllegalStateException("A started WASM policy is 
required to reload its policy");
+            }
+            wasm = (OpaReloadableWasmEvaluator) evaluator;
+        }
+        return wasm.reload();
+    }
+
+    public OpaPolicyReloadStatus getPolicyReloadStatus() {

Review Comment:
   Added in (4050b4d059fa).
   
   _Claude Code on behalf of oscerd_



##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java:
##########
@@ -100,11 +100,11 @@ public static Bundle loadPolicy(CamelContext 
camelContext, String location) thro
      * Builds a wasm evaluator from a bundle location, applying the validation 
and the entrypoint default in one place
      * so that the producer and the {@code OpaSecurityPolicy} construct it 
identically.
      */
-    public static OpaWasmEvaluator create(
-            CamelContext camelContext, String policyBundle, String entrypoint, 
int poolSize, long borrowTimeout,
-            String policyPath, String allowKey, String includeHeaders, String 
includeProperties, boolean includeBody,
-            boolean failOpen)
-            throws Exception {
+    /**

Review Comment:
   Fixed in (4050b4d059fa): the block is back on `create`, and 
`validateWasmOptions` keeps its own.
   
   _Claude Code on behalf of oscerd_



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