/*
 * 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.hudi.io;

import org.apache.hudi.common.engine.TaskContextSupplier;
import org.apache.hudi.common.fs.FSUtils;
import org.apache.hudi.common.model.HoodieBaseFile;
import org.apache.hudi.common.model.HoodieRecord;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.config.HoodieWriteConfig;
import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.storage.StoragePath;
import org.apache.hudi.table.HoodieTable;
import org.apache.hudi.table.marker.WriteMarkers;
import org.apache.hudi.table.marker.WriteMarkersFactory;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Iterator;

/**
 * A {@link FileGroupReaderBasedMergeHandle} that supports MERGE write incrementally(small data buffers).
 *
 * <P>This handle is needed for the first mini-batch write for COW data bucket
 * when the data bucket is written using multiple mini-batches.
 *
 * <p>For a new data buffer, it initializes and sets up the next file path to write, and closes
 * the file path when the data buffer writes finish. When next data buffer write starts,
 * {@link FlinkFileGroupReaderBasedIncrementalMergeHandle} will be used to write records into a rollover file.
 */
@Slf4j
public class FlinkFileGroupReaderBasedMergeHandle<T, I, K, O>
    extends FileGroupReaderBasedMergeHandle<T, I, K, O>
    implements MiniBatchHandle {

  public FlinkFileGroupReaderBasedMergeHandle(HoodieWriteConfig config, String instantTime, HoodieTable<T, I, K, O> hoodieTable,
                                              Iterator<HoodieRecord<T>> recordItr, String partitionPath, String fileId,
                                              TaskContextSupplier taskContextSupplier) {
    this(config, instantTime, hoodieTable, recordItr, partitionPath, fileId, taskContextSupplier, getLatestBaseFile(hoodieTable, partitionPath, fileId));
  }

  public FlinkFileGroupReaderBasedMergeHandle(HoodieWriteConfig config, String instantTime, HoodieTable<T, I, K, O> hoodieTable,
                                              Iterator<HoodieRecord<T>> recordItr, String partitionPath, String fileId,
                                              TaskContextSupplier taskContextSupplier, HoodieBaseFile hoodieBaseFile) {
    super(config, instantTime, hoodieTable, recordItr, partitionPath, fileId, taskContextSupplier, hoodieBaseFile, Option.empty());
    // delete invalid data files generated by task retry.
    if (getAttemptId() > 0) {
      deleteInvalidDataFile(getAttemptId() - 1);
    }
  }

  @Override
  protected long getMaxMemoryForMerge() {
    // the incoming records are already buffered on heap, and the underlying bytes are managed by memory pool
    // in Flink write buffer, so there is no need to spill.
    return Long.MAX_VALUE;
  }

  /**
   * The flink checkpoints start in sequence and asynchronously, when one write task finish the checkpoint(A)
   * (thus the fs view got the written data files some of which may be invalid),
   * it goes on with the next round checkpoint(B) write immediately,
   * if it tries to reuse the last small data bucket(small file) of an invalid data file,
   * finally, when the coordinator receives the checkpoint success event of checkpoint(A),
   * the invalid data file would be cleaned,
   * and this merger got a FileNotFoundException when it close the write file handle.
   *
   * <p> To solve, deletes the invalid data file eagerly
   * so that the invalid file small bucket would never be reused.
   *
   * @param lastAttemptId The last attempt ID
   */
  private void deleteInvalidDataFile(long lastAttemptId) {
    final String lastWriteToken = FSUtils.makeWriteToken(getPartitionId(), getStageId(), lastAttemptId);
    final String lastDataFileName = FSUtils.makeBaseFileName(instantTime,
        lastWriteToken, this.fileId, hoodieTable.getBaseFileExtension());
    final StoragePath path = makeNewFilePath(partitionPath, lastDataFileName);
    if (path.equals(oldFilePath)) {
      // In some rare cases, the old attempt file is used as the old base file to merge
      // because the flink index eagerly records that.
      //
      // The merge handle has the 'UPSERT' semantics, so there is no need to roll over
      // and the file can still be used as the merge base file.
      return;
    }
    try {
      if (storage.exists(path)) {
        log.info("Deleting invalid MERGE base file due to task retry: {}", lastDataFileName);
        storage.deleteFile(path);
      }
    } catch (IOException e) {
      throw new HoodieException("Error while deleting the MERGE base file due to task retry: " + lastDataFileName, e);
    }
  }

  @Override
  protected void createMarkerFile(String partitionPath, String dataFileName) {
    WriteMarkers writeMarkers = WriteMarkersFactory.get(config.getMarkersType(), hoodieTable, instantTime);
    writeMarkers.createIfNotExists(partitionPath, dataFileName, getIOType());
  }

  @Override
  boolean needsUpdateLocation() {
    // No need to update location for Flink hoodie records because all the records are pre-tagged
    // with the desired locations.
    return false;
  }

  @Override
  public void closeGracefully() {
    if (isClosed()) {
      return;
    }
    try {
      close();
    } catch (Throwable throwable) {
      log.error("Failed to close the MERGE handle", throwable);
      try {
        storage.deleteFile(newFilePath);
        log.info("Successfully deleted the intermediate MERGE data file: {}", newFilePath);
      } catch (IOException e) {
        // logging a warning and ignore the exception.
        log.warn("Failed to delete the intermediate MERGE data file: {}", newFilePath, e);

      }
    }
  }

  @Override
  public StoragePath getWritePath() {
    return newFilePath;
  }
}
