You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by co...@apache.org on 2026/04/27 18:19:28 UTC

(seatunnel) branch dev updated: [Fix][Connector-V2] Clean up file sink transaction parent dirs (#10815)

This is an automated email from the ASF dual-hosted git repository.

corgy-w pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git


The following commit(s) were added to refs/heads/dev by this push:
     new 527e2e31f9 [Fix][Connector-V2] Clean up file sink transaction parent dirs (#10815)
527e2e31f9 is described below

commit 527e2e31f9891edc615f4f88c5efed9ebf52082c
Author: yzeng1618 <yz...@gmail.com>
AuthorDate: Tue Apr 28 02:19:20 2026 +0800

    [Fix][Connector-V2] Clean up file sink transaction parent dirs (#10815)
---
 .../file/hadoop/HadoopFileSystemProxy.java         |  25 ++++
 .../sink/commit/FileSinkAggregatedCommitter.java   |  63 ++++++++-
 .../file/sink/writer/AbstractWriteStrategy.java    |  26 +++-
 ...oopFileSystemProxyDeleteEmptyDirectoryTest.java | 120 ++++++++++++++++
 .../commit/FileSinkAggregatedCommitterTest.java    | 115 ++++++++++++++++
 .../sink/writer/AbstractWriteStrategyTest.java     | 152 +++++++++++++++++++++
 6 files changed, 496 insertions(+), 5 deletions(-)

diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxy.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxy.java
index db067cac1f..a6578ea2db 100644
--- a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxy.java
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxy.java
@@ -93,6 +93,31 @@ public class HadoopFileSystemProxy implements Serializable, Closeable {
                 });
     }
 
+    public boolean deleteEmptyDirectory(@NonNull String filePath) throws IOException {
+        return execute(
+                () -> {
+                    Path path = new Path(filePath);
+                    FileSystem fileSystem = getFileSystem();
+                    try {
+                        if (!fileSystem.exists(path)
+                                || !fileSystem.getFileStatus(path).isDirectory()) {
+                            return false;
+                        }
+                        FileStatus[] children = fileSystem.listStatus(path);
+                        if (children != null && children.length > 0) {
+                            return false;
+                        }
+                        return fileSystem.delete(path, false);
+                    } catch (IOException e) {
+                        log.debug(
+                                "Skip deleting empty directory {}, it may be changed concurrently",
+                                filePath,
+                                e);
+                        return false;
+                    }
+                });
+    }
+
     public void renameFile(
             @NonNull String oldFilePath,
             @NonNull String newFilePath,
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitter.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitter.java
index 0c2614a2fe..2d0a7efd0e 100644
--- a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitter.java
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitter.java
@@ -21,19 +21,25 @@ import org.apache.seatunnel.api.sink.SinkAggregatedCommitter;
 import org.apache.seatunnel.connectors.seatunnel.file.config.HadoopConf;
 import org.apache.seatunnel.connectors.seatunnel.file.hadoop.HadoopFileSystemProxy;
 
+import org.apache.hadoop.fs.Path;
+
 import lombok.extern.slf4j.Slf4j;
 
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 @Slf4j
 public class FileSinkAggregatedCommitter
         implements SinkAggregatedCommitter<FileCommitInfo, FileAggregatedCommitInfo> {
     protected HadoopFileSystemProxy hadoopFileSystemProxy;
     private final HadoopConf hadoopConf;
+    private final Set<String> pendingUuidDirectories = new LinkedHashSet<>();
+    private final Set<String> pendingJobDirectories = new LinkedHashSet<>();
 
     public FileSinkAggregatedCommitter(HadoopConf hadoopConf) {
         this.hadoopConf = hadoopConf;
@@ -59,14 +65,16 @@ public class FileSinkAggregatedCommitter
                                 hadoopFileSystemProxy.renameFile(
                                         mvFileEntry.getKey(), mvFileEntry.getValue(), true);
                             }
+                            String transactionDir = entry.getKey();
                             // Data files are already committed after rename; tmp cleanup is
                             // best-effort and should not fail the whole checkpoint.
                             try {
-                                hadoopFileSystemProxy.deleteFile(entry.getKey());
+                                hadoopFileSystemProxy.deleteFile(transactionDir);
+                                registerTransactionParentDirectories(transactionDir);
                             } catch (Exception cleanupException) {
                                 log.warn(
                                         "delete transaction directory [{}] failed after successful commit, ignore this cleanup error.",
-                                        entry.getKey(),
+                                        transactionDir,
                                         cleanupException);
                             }
                         }
@@ -137,7 +145,9 @@ public class FileSinkAggregatedCommitter
                                 }
                             }
                             // delete the transaction dir
-                            hadoopFileSystemProxy.deleteFile(entry.getKey());
+                            String transactionDir = entry.getKey();
+                            hadoopFileSystemProxy.deleteFile(transactionDir);
+                            cleanupTransactionParentDirectories(transactionDir);
                         }
                     } catch (Exception e) {
                         log.error("abort aggregatedCommitInfo error ", e);
@@ -152,6 +162,51 @@ public class FileSinkAggregatedCommitter
      */
     @Override
     public void close() throws IOException {
-        hadoopFileSystemProxy.close();
+        try {
+            cleanupPendingTransactionParentDirectories();
+        } finally {
+            hadoopFileSystemProxy.close();
+        }
+    }
+
+    private void registerTransactionParentDirectories(String transactionDir) {
+        Path uuidDir = new Path(transactionDir).getParent();
+        if (uuidDir == null) {
+            return;
+        }
+        Path jobDir = uuidDir.getParent();
+        if (jobDir == null) {
+            return;
+        }
+        pendingUuidDirectories.add(uuidDir.toString());
+        pendingJobDirectories.add(jobDir.toString());
+    }
+
+    private void cleanupTransactionParentDirectories(String transactionDir) {
+        Path uuidDir = new Path(transactionDir).getParent();
+        if (uuidDir == null) {
+            return;
+        }
+        Path jobDir = uuidDir.getParent();
+        if (jobDir == null) {
+            return;
+        }
+        cleanupEmptyDirectory(uuidDir.toString());
+        cleanupEmptyDirectory(jobDir.toString());
+    }
+
+    private void cleanupPendingTransactionParentDirectories() {
+        pendingUuidDirectories.forEach(this::cleanupEmptyDirectory);
+        pendingJobDirectories.forEach(this::cleanupEmptyDirectory);
+        pendingUuidDirectories.clear();
+        pendingJobDirectories.clear();
+    }
+
+    private void cleanupEmptyDirectory(String directory) {
+        try {
+            hadoopFileSystemProxy.deleteEmptyDirectory(directory);
+        } catch (IOException e) {
+            log.warn("Failed to clean empty transaction parent directory: {}", directory, e);
+        }
     }
 }
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategy.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategy.java
index b445256e06..e4fcfa9bbb 100644
--- a/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategy.java
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategy.java
@@ -39,6 +39,7 @@ import org.apache.seatunnel.connectors.seatunnel.file.sink.state.FileSinkState;
 
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -289,8 +290,10 @@ public abstract class AbstractWriteStrategy<T> implements WriteStrategy<T> {
      * @param transactionId transaction id
      */
     public void abortPrepare(String transactionId) {
+        String transactionDir = getTransactionDir(transactionId);
         try {
-            hadoopFileSystemProxy.deleteFile(getTransactionDir(transactionId));
+            hadoopFileSystemProxy.deleteFile(transactionDir);
+            cleanupTransactionParentDirectories(transactionDir);
         } catch (IOException e) {
             throw new FileConnectorException(
                     CommonErrorCodeDeprecated.WRITER_OPERATION_FAILED,
@@ -301,6 +304,27 @@ public abstract class AbstractWriteStrategy<T> implements WriteStrategy<T> {
         }
     }
 
+    private void cleanupTransactionParentDirectories(String transactionDir) {
+        Path uuidDir = new Path(transactionDir).getParent();
+        if (uuidDir == null) {
+            return;
+        }
+        Path jobDir = uuidDir.getParent();
+        if (jobDir == null) {
+            return;
+        }
+        cleanupEmptyDirectory(uuidDir);
+        cleanupEmptyDirectory(jobDir);
+    }
+
+    private void cleanupEmptyDirectory(Path directory) {
+        try {
+            hadoopFileSystemProxy.deleteEmptyDirectory(directory.toString());
+        } catch (IOException e) {
+            log.warn("Failed to clean empty transaction parent directory: {}", directory, e);
+        }
+    }
+
     /**
      * when a checkpoint completed, file connector should begin a new transaction and generate new
      * transaction id
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxyDeleteEmptyDirectoryTest.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxyDeleteEmptyDirectoryTest.java
new file mode 100644
index 0000000000..ad140b63d8
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/hadoop/HadoopFileSystemProxyDeleteEmptyDirectoryTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.file.hadoop;
+
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+
+class HadoopFileSystemProxyDeleteEmptyDirectoryTest {
+
+    @Test
+    void shouldDeleteEmptyDirectory() throws Exception {
+        Path emptyDir = new Path("/tmp/empty");
+        FileSystem fs = Mockito.mock(FileSystem.class);
+        Mockito.when(fs.exists(emptyDir)).thenReturn(true);
+        Mockito.when(fs.getFileStatus(emptyDir)).thenReturn(directoryStatus(emptyDir));
+        Mockito.when(fs.listStatus(emptyDir)).thenReturn(new FileStatus[0]);
+        Mockito.when(fs.delete(emptyDir, false)).thenReturn(true);
+
+        try (HadoopFileSystemProxy proxy = newProxy(fs)) {
+            Assertions.assertTrue(proxy.deleteEmptyDirectory(emptyDir.toUri().toString()));
+        }
+
+        Mockito.verify(fs).delete(emptyDir, false);
+    }
+
+    @Test
+    void shouldSkipMissingFileAndNonEmptyDirectory() throws Exception {
+        Path missingPath = new Path("/tmp/missing");
+        Path regularFile = new Path("/tmp/data.txt");
+        Path nonEmptyDir = new Path("/tmp/non-empty");
+        FileSystem fs = Mockito.mock(FileSystem.class);
+        Mockito.when(fs.exists(missingPath)).thenReturn(false);
+        Mockito.when(fs.exists(regularFile)).thenReturn(true);
+        Mockito.when(fs.getFileStatus(regularFile)).thenReturn(fileStatus(regularFile));
+        Mockito.when(fs.exists(nonEmptyDir)).thenReturn(true);
+        Mockito.when(fs.getFileStatus(nonEmptyDir)).thenReturn(directoryStatus(nonEmptyDir));
+        Mockito.when(fs.listStatus(nonEmptyDir))
+                .thenReturn(new FileStatus[] {fileStatus(new Path(nonEmptyDir, "data.txt"))});
+
+        try (HadoopFileSystemProxy proxy = newProxy(fs)) {
+            Assertions.assertFalse(proxy.deleteEmptyDirectory(missingPath.toString()));
+            Assertions.assertFalse(proxy.deleteEmptyDirectory(regularFile.toString()));
+            Assertions.assertFalse(proxy.deleteEmptyDirectory(nonEmptyDir.toUri().toString()));
+        }
+
+        Mockito.verify(fs, Mockito.never()).delete(Mockito.any(Path.class), Mockito.anyBoolean());
+    }
+
+    @Test
+    void shouldIgnoreDirectoryChangedDuringEmptyDirectoryCheck() throws Exception {
+        Path changingDir = new Path("/tmp/changing");
+        FileSystem fs = Mockito.mock(FileSystem.class);
+        Mockito.when(fs.exists(changingDir)).thenReturn(true);
+        Mockito.when(fs.getFileStatus(changingDir)).thenReturn(directoryStatus(changingDir));
+        Mockito.when(fs.listStatus(changingDir)).thenThrow(new IOException("changed"));
+
+        try (HadoopFileSystemProxy proxy = newProxy(fs)) {
+            Assertions.assertFalse(proxy.deleteEmptyDirectory(changingDir.toUri().toString()));
+        }
+
+        Mockito.verify(fs, Mockito.never()).delete(Mockito.any(Path.class), Mockito.anyBoolean());
+    }
+
+    private static FileStatus directoryStatus(Path path) {
+        return new FileStatus(0, true, 1, 0, 0, path);
+    }
+
+    private static FileStatus fileStatus(Path path) {
+        return new FileStatus(1, false, 1, 0, 0, path);
+    }
+
+    private static HadoopFileSystemProxy newProxy(FileSystem fs) throws Exception {
+        HadoopFileSystemProxy proxy =
+                Mockito.mock(HadoopFileSystemProxy.class, Mockito.CALLS_REAL_METHODS);
+        set(proxy, "fileSystem", fs);
+        set(proxy, "isAuthTypeKerberos", false);
+        return proxy;
+    }
+
+    private static void set(Object target, String field, Object value) throws Exception {
+        Field f = null;
+        Class<?> cls = target.getClass();
+        while (cls != null) {
+            try {
+                f = cls.getDeclaredField(field);
+                break;
+            } catch (NoSuchFieldException ignore) {
+                cls = cls.getSuperclass();
+            }
+        }
+        if (f == null) {
+            throw new NoSuchFieldException(field);
+        }
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+}
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitterTest.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitterTest.java
new file mode 100644
index 0000000000..ab7b885376
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/commit/FileSinkAggregatedCommitterTest.java
@@ -0,0 +1,115 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.file.sink.commit;
+
+import org.apache.seatunnel.connectors.seatunnel.file.config.HadoopConf;
+import org.apache.seatunnel.connectors.seatunnel.file.hadoop.HadoopFileSystemProxy;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+class FileSinkAggregatedCommitterTest {
+
+    private static final String TMP_ROOT = "/tmp/seatunnel/seatunnel";
+    private static final String JOB_DIR = TMP_ROOT + "/job-1";
+    private static final String UUID_DIR = JOB_DIR + "/uuid-1";
+    private static final String TRANSACTION_DIR = UUID_DIR + "/T_job-1_uuid-1_0_1";
+    private static final String TEMP_FILE = TRANSACTION_DIR + "/NON_PARTITION/out.txt";
+    private static final String TARGET_FILE = "/warehouse/table/out.txt";
+
+    private static class TestableCommitter extends FileSinkAggregatedCommitter {
+        TestableCommitter() {
+            super(new HadoopConf("hdfs://dummy"));
+        }
+
+        void setFileSystemProxy(HadoopFileSystemProxy proxy) {
+            this.hadoopFileSystemProxy = proxy;
+        }
+    }
+
+    @Test
+    void shouldDeferEmptyTransactionParentDirectoryCleanupUntilClose() throws Exception {
+        HadoopFileSystemProxy fs = Mockito.mock(HadoopFileSystemProxy.class);
+        TestableCommitter committer = newCommitter(fs);
+
+        List<FileAggregatedCommitInfo> errors =
+                committer.commit(Collections.singletonList(newCommitInfo(true)));
+
+        Assertions.assertTrue(errors.isEmpty());
+        Mockito.verify(fs).renameFile(TEMP_FILE, TARGET_FILE, true);
+        Mockito.verify(fs).deleteFile(TRANSACTION_DIR);
+        Mockito.verify(fs, Mockito.never()).deleteEmptyDirectory(Mockito.anyString());
+
+        committer.close();
+
+        Mockito.verify(fs).deleteEmptyDirectory(UUID_DIR);
+        Mockito.verify(fs).deleteEmptyDirectory(JOB_DIR);
+        Mockito.verify(fs, Mockito.never()).deleteEmptyDirectory(TMP_ROOT);
+        Mockito.verify(fs).close();
+    }
+
+    @Test
+    void shouldCleanEmptyTransactionParentDirectoriesAfterAbort() throws Exception {
+        HadoopFileSystemProxy fs = Mockito.mock(HadoopFileSystemProxy.class);
+        TestableCommitter committer = newCommitter(fs);
+
+        committer.abort(Collections.singletonList(newCommitInfo(false)));
+
+        Mockito.verify(fs).deleteFile(TRANSACTION_DIR);
+        Mockito.verify(fs).deleteEmptyDirectory(UUID_DIR);
+        Mockito.verify(fs).deleteEmptyDirectory(JOB_DIR);
+        Mockito.verify(fs, Mockito.never()).deleteEmptyDirectory(TMP_ROOT);
+    }
+
+    @Test
+    void shouldIgnoreTransactionDirectoryCleanupFailureAfterCommit() throws Exception {
+        HadoopFileSystemProxy fs = Mockito.mock(HadoopFileSystemProxy.class);
+        Mockito.doThrow(new java.io.IOException("cleanup failed"))
+                .when(fs)
+                .deleteFile(TRANSACTION_DIR);
+        TestableCommitter committer = newCommitter(fs);
+
+        List<FileAggregatedCommitInfo> errors =
+                committer.commit(Collections.singletonList(newCommitInfo(true)));
+
+        Assertions.assertTrue(errors.isEmpty());
+        Mockito.verify(fs).renameFile(TEMP_FILE, TARGET_FILE, true);
+        Mockito.verify(fs).deleteFile(TRANSACTION_DIR);
+    }
+
+    private static TestableCommitter newCommitter(HadoopFileSystemProxy fs) {
+        TestableCommitter committer = new TestableCommitter();
+        committer.setFileSystemProxy(fs);
+        return committer;
+    }
+
+    private static FileAggregatedCommitInfo newCommitInfo(boolean withFileMove) {
+        LinkedHashMap<String, String> fileMoves = new LinkedHashMap<>();
+        if (withFileMove) {
+            fileMoves.put(TEMP_FILE, TARGET_FILE);
+        }
+        LinkedHashMap<String, LinkedHashMap<String, String>> transactionMap = new LinkedHashMap<>();
+        transactionMap.put(TRANSACTION_DIR, fileMoves);
+        return new FileAggregatedCommitInfo(transactionMap, new LinkedHashMap<>());
+    }
+}
diff --git a/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategyTest.java b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategyTest.java
new file mode 100644
index 0000000000..93d1c588ed
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/sink/writer/AbstractWriteStrategyTest.java
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.file.sink.writer;
+
+import org.apache.seatunnel.connectors.seatunnel.file.config.CompressFormat;
+import org.apache.seatunnel.connectors.seatunnel.file.config.FileBaseSinkOptions;
+import org.apache.seatunnel.connectors.seatunnel.file.exception.FileConnectorException;
+import org.apache.seatunnel.connectors.seatunnel.file.hadoop.HadoopFileSystemProxy;
+import org.apache.seatunnel.connectors.seatunnel.file.sink.config.FileSinkConfig;
+
+import org.apache.hadoop.fs.Path;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+
+class AbstractWriteStrategyTest {
+
+    private static final String TMP_PATH = "/tmp/seatunnel";
+    private static final String JOB_ID = "job-1";
+    private static final String UUID_PREFIX = "uuid-1";
+    private static final String TRANSACTION_ID = "T_job-1_uuid-1_0_1";
+
+    @Test
+    void shouldCleanEmptyTransactionParentDirectoriesAfterAbortPrepare() throws Exception {
+        TransactionPath transactionPath = newTransactionPath();
+        HadoopFileSystemProxy fs = Mockito.mock(HadoopFileSystemProxy.class);
+        TestWriteStrategy writeStrategy = newTestWriteStrategy(fs);
+
+        writeStrategy.abortPrepare(TRANSACTION_ID);
+
+        Mockito.verify(fs).deleteFile(transactionPath.transactionDir);
+        Mockito.verify(fs).deleteEmptyDirectory(transactionPath.uuidDir);
+        Mockito.verify(fs).deleteEmptyDirectory(transactionPath.jobDir);
+        Mockito.verify(fs, Mockito.never()).deleteEmptyDirectory(TMP_PATH);
+    }
+
+    @Test
+    void shouldHandleAbortPrepareCleanupFailures() throws Exception {
+        TransactionPath transactionPath = newTransactionPath();
+        HadoopFileSystemProxy fs = Mockito.mock(HadoopFileSystemProxy.class);
+        Mockito.doThrow(new IOException("cleanup failed"))
+                .when(fs)
+                .deleteEmptyDirectory(transactionPath.uuidDir);
+        TestWriteStrategy cleanupFailureStrategy = newTestWriteStrategy(fs);
+
+        Assertions.assertDoesNotThrow(() -> cleanupFailureStrategy.abortPrepare(TRANSACTION_ID));
+
+        Mockito.verify(fs).deleteFile(transactionPath.transactionDir);
+        Mockito.verify(fs).deleteEmptyDirectory(transactionPath.uuidDir);
+        Mockito.verify(fs).deleteEmptyDirectory(transactionPath.jobDir);
+
+        fs = Mockito.mock(HadoopFileSystemProxy.class);
+        Mockito.doThrow(new IOException("delete failed"))
+                .when(fs)
+                .deleteFile(transactionPath.transactionDir);
+        TestWriteStrategy deleteFailureStrategy = newTestWriteStrategy(fs);
+
+        Assertions.assertThrows(
+                FileConnectorException.class,
+                () -> deleteFailureStrategy.abortPrepare(TRANSACTION_ID));
+
+        Mockito.verify(fs).deleteFile(transactionPath.transactionDir);
+        Mockito.verify(fs, Mockito.never()).deleteEmptyDirectory(Mockito.anyString());
+    }
+
+    private static TestWriteStrategy newTestWriteStrategy(HadoopFileSystemProxy fs) {
+        TestWriteStrategy writeStrategy = new TestWriteStrategy(newFileSinkConfig());
+        writeStrategy.setFileSystemProxy(fs);
+        writeStrategy.setTransactionContext(JOB_ID, UUID_PREFIX);
+        return writeStrategy;
+    }
+
+    private static FileSinkConfig newFileSinkConfig() {
+        FileSinkConfig fileSinkConfig = Mockito.mock(FileSinkConfig.class);
+        Mockito.when(fileSinkConfig.getSinkColumnsIndexInRow()).thenReturn(Collections.emptyList());
+        Mockito.when(fileSinkConfig.getBatchSize()).thenReturn(1000);
+        Mockito.when(fileSinkConfig.getCompressFormat()).thenReturn(CompressFormat.NONE);
+        Mockito.when(fileSinkConfig.isSingleFileMode()).thenReturn(false);
+        Mockito.when(fileSinkConfig.getTmpPath()).thenReturn(TMP_PATH);
+        return fileSinkConfig;
+    }
+
+    private static TransactionPath newTransactionPath() {
+        String transactionDir =
+                String.join(
+                        File.separator,
+                        TMP_PATH,
+                        FileBaseSinkOptions.SEATUNNEL,
+                        JOB_ID,
+                        UUID_PREFIX,
+                        TRANSACTION_ID);
+        String uuidDir = new Path(transactionDir).getParent().toString();
+        String jobDir = new Path(uuidDir).getParent().toString();
+        return new TransactionPath(transactionDir, uuidDir, jobDir);
+    }
+
+    private static class TransactionPath {
+        private final String transactionDir;
+        private final String uuidDir;
+        private final String jobDir;
+
+        private TransactionPath(String transactionDir, String uuidDir, String jobDir) {
+            this.transactionDir = transactionDir;
+            this.uuidDir = uuidDir;
+            this.jobDir = jobDir;
+        }
+    }
+
+    private static class TestWriteStrategy extends AbstractWriteStrategy<Object> {
+
+        private TestWriteStrategy(FileSinkConfig fileSinkConfig) {
+            super(fileSinkConfig);
+        }
+
+        private void setFileSystemProxy(HadoopFileSystemProxy proxy) {
+            this.hadoopFileSystemProxy = proxy;
+        }
+
+        private void setTransactionContext(String jobId, String uuidPrefix) {
+            this.jobId = jobId;
+            this.uuidPrefix = uuidPrefix;
+        }
+
+        @Override
+        public Object getOrCreateOutputStream(String path) {
+            return new Object();
+        }
+
+        @Override
+        public void finishAndCloseFile() {}
+    }
+}