/*
 * 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.spark.storage

import org.apache.spark.SparkException
import org.apache.spark.storage.LogBlockType.LogBlockType

/**
 * LogBlockIdGenerator is responsible for generating unique LogBlockIds for log blocks.
 */
trait LogBlockIdGenerator {
  // The log block type that this generator supports.
  def logBlockType: LogBlockType

  // Generates a unique LogBlockId based on the last log time and executor ID.
  protected def genUniqueBlockId(lastLogTime: Long, executorId: String): LogBlockId

  /**
   * Generates a new LogBlockId based on the last log time and executor ID. Make sure that
   * the generated LogBlockId has the same log block type as this generator.
   *
   * @param lastLogTime The timestamp of the last log entry.
   * @param executorId The ID of the executor generating the log block.
   */
  final def nextBlockId(lastLogTime: Long, executorId: String): LogBlockId = {
    val blockId = genUniqueBlockId(lastLogTime, executorId)
    if (blockId.logBlockType != this.logBlockType) {
      throw SparkException.internalError(
        "BlockId generated by LogBlockIdGenerator does not match " +
        s"the expected log block type: ${blockId.logBlockType} != ${this.logBlockType}")
    }
    blockId
  }
}

class PythonWorkerLogBlockIdGenerator(
    sessionId: String,
    workerId: String)
  extends LogBlockIdGenerator {

  override def logBlockType: LogBlockType = LogBlockType.PYTHON_WORKER

  override protected def genUniqueBlockId(lastLogTime: Long, executorId: String): LogBlockId =
    PythonWorkerLogBlockId(lastLogTime, executorId, sessionId, workerId)
}
