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


##########
components/camel-opa/src/main/java/org/apache/camel/component/opa/OpaWasmEvaluator.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * 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.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.concurrent.TimeoutException;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.styra.opa.wasm.OpaPolicy;
+import org.apache.camel.CamelContext;
+import org.apache.camel.support.ResourceHelper;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
+
+/**
+ * Evaluates the policy in-process from a WebAssembly bundle produced by 
{@code opa build -t wasm}.
+ * <p/>
+ * No OPA server is involved, so there is no network hop and no unreachable 
policy decision point - at the cost of the
+ * policy being a build-time artefact rather than something a server 
distributes and updates.
+ */
+public class OpaWasmEvaluator extends OpaPolicyEvaluator implements 
AutoCloseable {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+    private static final String POLICY_WASM = "policy.wasm";
+    private static final String DATA_JSON = "data.json";
+
+    private final OpaWasmPolicyPool pool;
+    private final String entrypoint;
+    private final String data;
+
+    public OpaWasmEvaluator(byte[] wasm, String data, String entrypoint, int 
poolSize, long borrowTimeout,
+                            String policyPath, String allowKey, String 
includeHeaders, String includeProperties,
+                            boolean includeBody, boolean failOpen) {
+        super(policyPath, allowKey, includeHeaders, includeProperties, 
includeBody, failOpen);
+        this.entrypoint = entrypoint;
+        this.data = data;
+        // OpaPolicy carries mutable input/data and is not thread-safe, while 
a Camel producer is invoked
+        // concurrently - so each exchange borrows its own instance rather 
than sharing one
+        this.pool = new OpaWasmPolicyPool(() -> 
OpaPolicy.builder().withPolicy(wasm).build(), poolSize, borrowTimeout);
+        // fail at startup rather than on the first exchange: the OpaPolicy 
constructor is what rejects a module
+        // that is not a valid OPA bundle, and the pool creates instances 
lazily
+        try (OpaWasmPolicyPool.Lease warmup = pool.borrow()) {
+            prepare(warmup.policy());
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new IllegalStateException("Interrupted while loading the 
WebAssembly policy", e);
+        } catch (TimeoutException e) {
+            throw new IllegalStateException("Timed out loading the WebAssembly 
policy", e);
+        }
+    }
+
+    /**
+     * Applies the entrypoint and data to a borrowed instance.
+     * <p/>
+     * This has to happen on every borrow, not once when the instance is 
built: returning a {@link OpaPolicyPool.Loan}
+     * calls {@code OpaPolicy.reset()}, which clears the data and sets the 
entrypoint back to 0. An instance configured
+     * only at creation would therefore evaluate whatever rule happens to be 
entrypoint 0 from its second use onwards -
+     * a different policy deciding, silently.

Review Comment:
   Verified and agreed, though the fix belongs upstream of this PR. 
`DefaultResourceResolvers.HttpResource`:
   
   ```java
   public InputStream getInputStream() throws IOException {
       URLConnection con = URI.create(getLocation()).toURL().openConnection();
       con.setUseCaches(false);
       try {
           setContentType(con.getContentType());
           return con.getInputStream();
   ```
   
   No `setConnectTimeout`, no `setReadTimeout`, and the JDK default for both is 
`0` — wait indefinitely. `exists()` does the same. So it is not the 
`policyBundle` option's behaviour but `camel-base-engine`'s, shared by every 
component that resolves an `http:` resource.
   
   You are right about the blast radius here specifically, and it is slightly 
worse than "stalls the endpoint": `loadPolicy` runs in `doStart()`, and the 
warmup borrow @davsclaus asked for is in the evaluator's constructor, so a 
policy server that accepts the connection and then does not answer stalls 
`CamelContext` startup rather than failing the one route. A *refused* 
connection fails fast, which is why this is the kind of thing that never 
reproduces locally.
   
   Filed as 
**[CAMEL-24756](https://issues.apache.org/jira/browse/CAMEL-24756)** against 
`camel-base-engine` — timeouts on both `getInputStream()` and `exists()`, 
defaulted and overridable, with an upgrade-guide note since it changes "wait 
forever" into "fail after N seconds". Left unassigned: it changes a default 
across many components and wants a committer's view before someone starts.
   
   I did **not** put the caveat in the `policyBundle` description, since it 
would be documenting core behaviour as if it were this option's and would 
invite the same sentence on every component that takes a resource location. It 
is in the component docs instead, where the advice is actionable:
   
   > Prefer `classpath:` or `file:` for a bundle shipped with the application, 
which is what a build-time artefact usually is. The bundle is fetched when the 
endpoint starts, and Camel resolves an `http:` resource with no connect or read 
timeout (CAMEL-24756), so a policy server that accepts the connection and then 
does not answer stalls `CamelContext` startup rather than failing the one route.
   
   _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