rzo1 commented on code in PR #1870:
URL: https://github.com/apache/stormcrawler/pull/1870#discussion_r3040797935


##########
external/opensearch/src/main/java/org/apache/stormcrawler/opensearch/DelegateRefresher.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.stormcrawler.opensearch;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
+import org.apache.stormcrawler.JSONResource;
+import org.opensearch.action.get.GetRequest;
+import org.opensearch.action.get.GetResponse;
+import org.opensearch.client.RequestOptions;
+import org.opensearch.client.RestHighLevelClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Loads a delegate class that implements both a required base type and {@link 
JSONResource}, then
+ * periodically refreshes its configuration from OpenSearch. Used by {@link
+ * org.apache.stormcrawler.opensearch.filtering.JSONURLFilterWrapper} and 
{@link
+ * org.apache.stormcrawler.opensearch.parse.filter.JSONResourceWrapper} to 
eliminate duplicated
+ * setup/refresh/cleanup logic.
+ *
+ * @param <T> the base type that the delegate must extend (e.g. URLFilter or 
ParseFilter)
+ */
+public class DelegateRefresher<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(DelegateRefresher.class);
+
+    private final T delegate;
+    private Timer refreshTimer;
+    private RestHighLevelClient osClient;
+
+    /**
+     * Creates a refresher by loading the delegate class from the JSON 
configuration.
+     *
+     * @param baseType the required base class (e.g. URLFilter.class or 
ParseFilter.class)
+     * @param stormConf the Storm configuration map
+     * @param filterParams the JSON params node containing "delegate" and 
optional "refresh"
+     * @param configurer callback to configure the delegate after instantiation
+     */
+    public DelegateRefresher(
+            Class<T> baseType,
+            Map<String, Object> stormConf,
+            JsonNode filterParams,
+            DelegateConfigure<T> configurer) {
+
+        JsonNode delegateNode = filterParams.get("delegate");
+        if (delegateNode == null) {
+            throw new RuntimeException("delegateNode undefined!");
+        }
+
+        String delegateClassName = null;
+        JsonNode node = delegateNode.get("class");
+        if (node != null && node.isTextual()) {
+            delegateClassName = node.asText();
+        }
+        if (delegateClassName == null) {
+            throw new RuntimeException(baseType.getSimpleName() + " delegate 
class undefined!");
+        }
+
+        try {
+            Class<?> filterClass = Class.forName(delegateClassName);
+
+            if (!baseType.isAssignableFrom(filterClass)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not extend " + 
baseType.getName());
+            }
+
+            @SuppressWarnings("unchecked")
+            T instance = (T) 
filterClass.getDeclaredConstructor().newInstance();
+
+            if (!(instance instanceof JSONResource)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not implement 
JSONResource");
+            }
+
+            this.delegate = instance;
+        } catch (RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            LOG.error("Can't setup {}: {}", delegateClassName, e);
+            throw new RuntimeException("Can't setup " + delegateClassName, e);
+        }
+
+        // configure the delegate
+        JsonNode paramsNode = delegateNode.get("params");
+        configurer.configure(delegate, stormConf, paramsNode);
+
+        // set up periodic refresh from OpenSearch
+        int refreshRate = 600;
+        node = filterParams.get("refresh");
+        if (node != null && node.isInt()) {
+            refreshRate = node.asInt(refreshRate);
+        }
+
+        final JSONResource resource = (JSONResource) delegate;
+
+        refreshTimer = new Timer();
+        refreshTimer.schedule(
+                new TimerTask() {
+                    public void run() {
+                        if (osClient == null) {
+                            try {
+                                osClient = 
OpenSearchConnection.getClient(stormConf, "config");
+                            } catch (Exception e) {
+                                LOG.error("Exception while creating OpenSearch 
connection", e);
+                            }
+                        }
+                        if (osClient != null) {
+                            LOG.info("Reloading json resources from 
OpenSearch");
+                            try {
+                                GetResponse response =
+                                        osClient.get(
+                                                new GetRequest(
+                                                        "config", 
resource.getResourceFile()),
+                                                RequestOptions.DEFAULT);
+                                resource.loadJSONResources(
+                                        new 
ByteArrayInputStream(response.getSourceAsBytes()));
+                            } catch (Exception e) {
+                                LOG.error("Can't load config from OpenSearch", 
e);
+                            }
+                        }
+                    }
+                },
+                0,

Review Comment:
   The initial delay of 0 means the timer fires on a background thread during 
configure(), before the bolt is fully initialised. If 
OpenSearchConnection.getClient() fails, it's silently swallowed. This existed 
in the original code, but since this is a rewrite it would be a good moment to 
either change the initial delay to refreshRate * 1000L (fire on the same 
schedule as subsequent runs) or if immediate execution is intentional, we 
should add a comment.



##########
external/opensearch/src/main/java/org/apache/stormcrawler/opensearch/DelegateRefresher.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.stormcrawler.opensearch;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
+import org.apache.stormcrawler.JSONResource;
+import org.opensearch.action.get.GetRequest;
+import org.opensearch.action.get.GetResponse;
+import org.opensearch.client.RequestOptions;
+import org.opensearch.client.RestHighLevelClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Loads a delegate class that implements both a required base type and {@link 
JSONResource}, then
+ * periodically refreshes its configuration from OpenSearch. Used by {@link
+ * org.apache.stormcrawler.opensearch.filtering.JSONURLFilterWrapper} and 
{@link
+ * org.apache.stormcrawler.opensearch.parse.filter.JSONResourceWrapper} to 
eliminate duplicated
+ * setup/refresh/cleanup logic.
+ *
+ * @param <T> the base type that the delegate must extend (e.g. URLFilter or 
ParseFilter)
+ */
+public class DelegateRefresher<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(DelegateRefresher.class);
+
+    private final T delegate;
+    private Timer refreshTimer;
+    private RestHighLevelClient osClient;
+
+    /**
+     * Creates a refresher by loading the delegate class from the JSON 
configuration.
+     *
+     * @param baseType the required base class (e.g. URLFilter.class or 
ParseFilter.class)
+     * @param stormConf the Storm configuration map
+     * @param filterParams the JSON params node containing "delegate" and 
optional "refresh"
+     * @param configurer callback to configure the delegate after instantiation
+     */
+    public DelegateRefresher(
+            Class<T> baseType,
+            Map<String, Object> stormConf,
+            JsonNode filterParams,
+            DelegateConfigure<T> configurer) {
+
+        JsonNode delegateNode = filterParams.get("delegate");
+        if (delegateNode == null) {
+            throw new RuntimeException("delegateNode undefined!");
+        }
+
+        String delegateClassName = null;
+        JsonNode node = delegateNode.get("class");
+        if (node != null && node.isTextual()) {
+            delegateClassName = node.asText();
+        }
+        if (delegateClassName == null) {
+            throw new RuntimeException(baseType.getSimpleName() + " delegate 
class undefined!");
+        }
+
+        try {
+            Class<?> filterClass = Class.forName(delegateClassName);
+
+            if (!baseType.isAssignableFrom(filterClass)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not extend " + 
baseType.getName());
+            }
+
+            @SuppressWarnings("unchecked")
+            T instance = (T) 
filterClass.getDeclaredConstructor().newInstance();
+
+            if (!(instance instanceof JSONResource)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not implement 
JSONResource");
+            }
+
+            this.delegate = instance;
+        } catch (RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            LOG.error("Can't setup {}: {}", delegateClassName, e);
+            throw new RuntimeException("Can't setup " + delegateClassName, e);
+        }
+
+        // configure the delegate
+        JsonNode paramsNode = delegateNode.get("params");
+        configurer.configure(delegate, stormConf, paramsNode);
+
+        // set up periodic refresh from OpenSearch
+        int refreshRate = 600;
+        node = filterParams.get("refresh");
+        if (node != null && node.isInt()) {

Review Comment:
   The Javadoc example shows "refresh": "60" (a string), but node.isInt() 
returns false for JSON strings. So passing "60" silently falls back to the 
600-second default. The original code had this same bug. Since this is being 
rewritten, it would be easy to fix with node.isInt() || node.isTextual() and 
using node.asInt() which handles both.



##########
external/opensearch/src/main/java/org/apache/stormcrawler/opensearch/DelegateRefresher.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.stormcrawler.opensearch;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
+import org.apache.stormcrawler.JSONResource;
+import org.opensearch.action.get.GetRequest;
+import org.opensearch.action.get.GetResponse;
+import org.opensearch.client.RequestOptions;
+import org.opensearch.client.RestHighLevelClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Loads a delegate class that implements both a required base type and {@link 
JSONResource}, then
+ * periodically refreshes its configuration from OpenSearch. Used by {@link
+ * org.apache.stormcrawler.opensearch.filtering.JSONURLFilterWrapper} and 
{@link
+ * org.apache.stormcrawler.opensearch.parse.filter.JSONResourceWrapper} to 
eliminate duplicated
+ * setup/refresh/cleanup logic.
+ *
+ * @param <T> the base type that the delegate must extend (e.g. URLFilter or 
ParseFilter)
+ */
+public class DelegateRefresher<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(DelegateRefresher.class);
+
+    private final T delegate;
+    private Timer refreshTimer;
+    private RestHighLevelClient osClient;
+
+    /**
+     * Creates a refresher by loading the delegate class from the JSON 
configuration.
+     *
+     * @param baseType the required base class (e.g. URLFilter.class or 
ParseFilter.class)
+     * @param stormConf the Storm configuration map
+     * @param filterParams the JSON params node containing "delegate" and 
optional "refresh"
+     * @param configurer callback to configure the delegate after instantiation
+     */
+    public DelegateRefresher(
+            Class<T> baseType,
+            Map<String, Object> stormConf,
+            JsonNode filterParams,
+            DelegateConfigure<T> configurer) {
+
+        JsonNode delegateNode = filterParams.get("delegate");
+        if (delegateNode == null) {
+            throw new RuntimeException("delegateNode undefined!");
+        }
+
+        String delegateClassName = null;
+        JsonNode node = delegateNode.get("class");
+        if (node != null && node.isTextual()) {
+            delegateClassName = node.asText();
+        }
+        if (delegateClassName == null) {
+            throw new RuntimeException(baseType.getSimpleName() + " delegate 
class undefined!");
+        }
+
+        try {
+            Class<?> filterClass = Class.forName(delegateClassName);
+
+            if (!baseType.isAssignableFrom(filterClass)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not extend " + 
baseType.getName());
+            }
+
+            @SuppressWarnings("unchecked")
+            T instance = (T) 
filterClass.getDeclaredConstructor().newInstance();
+
+            if (!(instance instanceof JSONResource)) {
+                throw new RuntimeException(
+                        "Filter " + delegateClassName + " does not implement 
JSONResource");
+            }
+
+            this.delegate = instance;
+        } catch (RuntimeException e) {
+            throw e;
+        } catch (Exception e) {
+            LOG.error("Can't setup {}: {}", delegateClassName, e);
+            throw new RuntimeException("Can't setup " + delegateClassName, e);
+        }
+
+        // configure the delegate
+        JsonNode paramsNode = delegateNode.get("params");
+        configurer.configure(delegate, stormConf, paramsNode);
+
+        // set up periodic refresh from OpenSearch
+        int refreshRate = 600;
+        node = filterParams.get("refresh");
+        if (node != null && node.isInt()) {
+            refreshRate = node.asInt(refreshRate);
+        }
+
+        final JSONResource resource = (JSONResource) delegate;
+
+        refreshTimer = new Timer();
+        refreshTimer.schedule(
+                new TimerTask() {
+                    public void run() {
+                        if (osClient == null) {
+                            try {
+                                osClient = 
OpenSearchConnection.getClient(stormConf, "config");
+                            } catch (Exception e) {
+                                LOG.error("Exception while creating OpenSearch 
connection", e);
+                            }
+                        }
+                        if (osClient != null) {
+                            LOG.info("Reloading json resources from 
OpenSearch");
+                            try {
+                                GetResponse response =
+                                        osClient.get(
+                                                new GetRequest(
+                                                        "config", 
resource.getResourceFile()),
+                                                RequestOptions.DEFAULT);
+                                resource.loadJSONResources(
+                                        new 
ByteArrayInputStream(response.getSourceAsBytes()));
+                            } catch (Exception e) {
+                                LOG.error("Can't load config from OpenSearch", 
e);
+                            }
+                        }
+                    }
+                },
+                0,
+                refreshRate * 1000L);
+    }
+
+    /** Returns the delegate instance. */
+    public T getDelegate() {
+        return delegate;
+    }
+
+    /** Cancels the refresh timer and closes the OpenSearch client. */
+    public void cleanup() {

Review Comment:
   `cleanup()` is not idempotent in a thread-safe way. 
   
   `refreshTimer.cancel() `is safe to call twice, while `osClient.close()` on 
an already-closed client may throw depending on the OpenSearch client version. 
The `osClient` reference is never nulled out after close, so a second call 
would attempt to close it again. Worth adding `osClient = null `after closing, 
matching the pattern used in the timer task for lazy init.
   
   



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