/*
 * 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.util

import scala.collection.mutable

import org.apache.spark.{SparkEnv, SparkException}

private[spark] object SparkClosureCleaner {
  /**
   * Clean the given closure in place.
   *
   * More specifically, this renders the given closure serializable as long as it does not
   * explicitly reference unserializable objects.
   *
   * @param closure           the closure to clean
   * @param checkSerializable whether to verify that the closure is serializable after cleaning
   * @param cleanTransitively whether to clean enclosing closures transitively
   * @return Cleaned closure if it was actually cleaned or the original closure otherwise
   */
  def clean[F <: AnyRef](
      closure: F,
      checkSerializable: Boolean = true,
      cleanTransitively: Boolean = true): F = {
    val cleanedClosureOpt = ClosureCleaner.clean(closure, cleanTransitively, mutable.Map.empty)
    if (cleanedClosureOpt.isDefined) {
      val cleanedClosure = cleanedClosureOpt.get
      try {
        if (checkSerializable && SparkEnv.get != null) {
          SparkEnv.get.closureSerializer.newInstance().serialize(cleanedClosure: AnyRef)
        }
      } catch {
        case ex: Exception => throw new SparkException("Task not serializable", ex)
      }
      cleanedClosure
    } else {
      closure
    }
  }
}
