Copilot commented on code in PR #2560:
URL: https://github.com/apache/iggy/pull/2560#discussion_r2693288288


##########
foreign/java/external-processors/iggy-connector-flink/iggy-connector-library/src/main/java/org/apache/iggy/connector/flink/sink/IggySinkWriter.java:
##########
@@ -184,7 +211,16 @@ public void flush(boolean endOfInput) throws IOException {
     public void close() throws Exception {
         // Flush any remaining buffered records
         flush(true);
-        // Note: HTTP client doesn't have close() method - connections managed 
by Java HttpClient pool
+
+        // Close TCP client if applicable (TCP clients need explicit close)
+        if (iggyClient instanceof IggyTcpClient) {
+            log.debug("Closing TCP client connection");
+            // TCP client connections are managed internally and closed when 
JVM exits
+            // or when connection pool is explicitly closed
+        }
+        // HTTP client doesn't need explicit close - connections managed by 
Java HttpClient pool

Review Comment:
   The close() method checks if the client is a TCP client but doesn't actually 
call any close method on it. If TCP clients don't need explicit cleanup, this 
instanceof check and the empty block add unnecessary complexity. Consider 
removing the instanceof check entirely, or if TCP clients will need cleanup in 
the future, add a TODO comment explaining what needs to be done.
   ```suggestion
           // Underlying Iggy clients manage their own connections; no explicit 
close required here.
   ```



##########
foreign/java/external-processors/iggy-connector-flink/iggy-connector-library/src/main/java/org/apache/iggy/connector/flink/sink/IggySinkWriter.java:
##########
@@ -120,6 +120,32 @@ public IggySinkWriter(
         this.buffer = new ArrayList<>(batchSize);
         this.lastFlushTime = System.currentTimeMillis();
         this.totalWritten = 0;
+
+        log.info("IggySinkWriter initialized with transport type: {}", 
connectionConfig.getTransportType());
+    }
+
+    private static void validateNotNull(Object value, String name) {
+        if (value == null) {
+            throw new IllegalArgumentException(name + " cannot be null");
+        }
+    }
+
+    private static void validateNotBlank(String value, String name) {
+        if (StringUtils.isBlank(value)) {
+            throw new IllegalArgumentException(name + " cannot be null or 
empty");
+        }
+    }
+
+    private static void validatePositive(int value, String name) {
+        if (value <= 0) {
+            throw new IllegalArgumentException(name + " must be > 0");
+        }
+    }
+
+    private static void validatePositiveDuration(Duration value, String name) {
+        if (value == null || value.isNegative()) {
+            throw new IllegalArgumentException(name + " must be positive");

Review Comment:
   The validation allows zero duration (Duration.ZERO), but the error message 
says 'must be positive'. A zero flush interval would mean immediate flushing 
which may not be intended. Either allow zero explicitly by adjusting the error 
message to 'must be non-negative', or check for zero and negative values with 
`value.isNegative() || value.isZero()` to enforce truly positive durations.
   ```suggestion
               throw new IllegalArgumentException(name + " must be 
non-negative");
   ```



##########
foreign/java/external-processors/iggy-connector-flink/iggy-connector-library/src/main/java/org/apache/iggy/connector/flink/IggyClientFactory.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.iggy.connector.flink;
+
+import org.apache.iggy.client.blocking.IggyBaseClient;
+import org.apache.iggy.client.blocking.http.IggyHttpClient;
+import org.apache.iggy.client.blocking.tcp.IggyTcpClient;
+import org.apache.iggy.connector.config.IggyConnectionConfig;
+import org.apache.iggy.connector.config.TransportType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Serializable;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+/**
+ * Factory for creating Iggy clients based on connection configuration.
+ * <p>
+ * Supports both HTTP and TCP transport protocols, providing a unified
+ * interface for client creation across the Flink connector.
+ *
+ * <p>Example usage:
+ * <pre>{@code
+ * IggyConnectionConfig config = IggyConnectionConfig.builder()
+ *     .serverAddress("localhost")
+ *     .transportType(TransportType.TCP)
+ *     .tcpPort(8090)
+ *     .username("iggy")
+ *     .password("iggy")
+ *     .build();
+ *
+ * IggyBaseClient client = IggyClientFactory.createClient(config);
+ * }</pre>
+ */
+public final class IggyClientFactory implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+    private static final Logger log = 
LoggerFactory.getLogger(IggyClientFactory.class);
+
+    private IggyClientFactory() {
+        // Utility class
+    }
+
+    /**
+     * Creates an Iggy client based on the connection configuration.
+     * <p>
+     * The client type (HTTP or TCP) is determined by the {@link TransportType}
+     * configured in the connection config. The client is automatically 
connected
+     * and authenticated.
+     *
+     * @param config the connection configuration
+     * @return a connected and authenticated Iggy client
+     * @throws RuntimeException if client creation or connection fails
+     */
+    public static IggyBaseClient createClient(IggyConnectionConfig config) {
+        TransportType transportType = config.getTransportType();
+
+        log.info("Creating Iggy client with transport type: {}", 
transportType);
+
+        switch (transportType) {
+            case TCP:
+                return createTcpClient(config);
+            case HTTP:
+            default:
+                return createHttpClient(config);
+        }
+    }
+
+    /**
+     * Creates an HTTP Iggy client.
+     *
+     * @param config the connection configuration
+     * @return a connected and authenticated HTTP client
+     */
+    private static IggyBaseClient createHttpClient(IggyConnectionConfig 
config) {
+        try {
+            String host = extractHost(config.getServerAddress());
+            int port = config.getHttpPort();
+
+            String httpUrl = buildHttpUrl(host, port, config.isEnableTls());
+
+            log.debug("Creating HTTP client for URL: {}", httpUrl);
+
+            IggyHttpClient httpClient = new IggyHttpClient(httpUrl);
+            httpClient.users().login(config.getUsername(), 
config.getPassword());
+
+            log.info("Successfully created and authenticated HTTP client to 
{}", httpUrl);
+            return httpClient;
+
+        } catch (RuntimeException e) {
+            throw new RuntimeException("Failed to create HTTP Iggy client: " + 
e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Creates a TCP Iggy client.
+     *
+     * @param config the connection configuration
+     * @return a connected and authenticated TCP client
+     */
+    private static IggyBaseClient createTcpClient(IggyConnectionConfig config) 
{
+        try {
+            String host = extractHost(config.getServerAddress());
+            int port = config.getTcpPort();
+
+            log.debug("Creating TCP client for {}:{}", host, port);
+
+            IggyTcpClient tcpClient = IggyTcpClient.builder()
+                    .host(host)
+                    .port(port)
+                    .credentials(config.getUsername(), config.getPassword())
+                    .tls(config.isEnableTls())
+                    .build();
+
+            log.info("Successfully created and authenticated TCP client to 
{}:{}", host, port);
+            return tcpClient;
+
+        } catch (RuntimeException e) {
+            throw new RuntimeException("Failed to create TCP Iggy client: " + 
e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Extracts the host from a server address.
+     * <p>
+     * Handles various address formats:
+     * <ul>
+     *   <li>Plain hostname: "localhost"</li>
+     *   <li>Host with port: "localhost:8090"</li>
+     *   <li>Full URL: "http://localhost:3000";</li>
+     * </ul>
+     *
+     * @param serverAddress the server address
+     * @return the extracted host
+     */
+    static String extractHost(String serverAddress) {
+        if (serverAddress == null || serverAddress.isBlank()) {
+            throw new IllegalArgumentException("serverAddress cannot be null 
or blank");
+        }
+
+        String address = serverAddress.trim();
+
+        // If it contains a scheme, parse as URI
+        if (address.contains("://")) {
+            try {
+                URI uri = new URI(address);
+                String host = uri.getHost();
+                if (host == null || host.isBlank()) {
+                    throw new IllegalArgumentException("Cannot extract host 
from URI: " + serverAddress);
+                }
+                return host;
+            } catch (URISyntaxException e) {
+                throw new IllegalArgumentException("Invalid server address 
format: " + serverAddress, e);
+            }
+        }
+
+        // If it contains a port separator, extract the host part
+        if (address.contains(":")) {
+            String[] parts = address.split(":");
+            if (parts.length >= 1 && !parts[0].isBlank()) {
+                return parts[0];
+            }
+            throw new IllegalArgumentException("Cannot extract host from 
address: " + serverAddress);
+        }

Review Comment:
   The host extraction logic for addresses with colons can fail for IPv6 
addresses (e.g., '[::1]:8090' or '2001:db8::1'). IPv6 addresses contain 
multiple colons which would cause incorrect splitting. Consider handling IPv6 
addresses explicitly, either by checking for brackets or by using more 
sophisticated URI parsing for all cases.



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