<commit_before>/*
 * Copyright 2014–2016 SlamData Inc.
 *
 * Licensed 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 quasar.physical.sparkcore.fs

import quasar.Predef._
import quasar.{Data, LogicalPlan, PhaseResult, PhaseResults, PhaseResultT, PlannerErrT}
import quasar.Planner._
import quasar.contrib.matryoshka._
import quasar.contrib.pathy._
import quasar.effect.{KeyValueStore, MonotonicSeq, Read}
import quasar.fp._
import quasar.fp.eitherT._
import quasar.fp.free._
import quasar.fs._, FileSystemError._, QueryFile._
import quasar.qscript._

import org.apache.spark._
import org.apache.spark.rdd._
import matryoshka._, Recursive.ops._, FunctorT.ops._
import scalaz._, Scalaz._
import scalaz.concurrent.Task

object queryfile {

  type SparkQScript[A] = QScriptShiftRead[Fix, A]

  final case class Input(
    fromFile: (SparkContext, AFile) => Task[RDD[String]],
    store: (RDD[Data], AFile) => Task[Unit],
    fileExists: AFile => Task[Boolean],
    listContents: ADir => EitherT[Task, FileSystemError, Set[PathSegment]],
    readChunkSize: () => Int
  )

  type SparkContextRead[A] = Read[SparkContext, A]

  def chrooted[S[_]](input: Input, prefix: ADir)(implicit
    s0: Task :<: S,
    s1: SparkContextRead :<: S,
    s2: MonotonicSeq :<: S,
    s3: KeyValueStore[ResultHandle, RddState, ?] :<: S
  ): QueryFile ~> Free[S, ?] =
    flatMapSNT(interpreter(input)) compose chroot.queryFile[QueryFile](prefix)

  def interpreter[S[_]](input: Input)(implicit
    s0: Task :<: S,
    s1: SparkContextRead :<: S,
    s2: MonotonicSeq :<: S,
    s3: KeyValueStore[ResultHandle, RddState, ?] :<: S
  ): QueryFile ~> Free[S, ?] = {

    val optimize = new Optimize[Fix]

    def toQScript(lp: Fix[LogicalPlan]): FileSystemErrT[PhaseResultT[Free[S, ?], ?], Fix[SparkQScript]] = {
      val lc: DiscoverPath.ListContents[FileSystemErrT[PhaseResultT[Free[S, ?],?],?]] =
        (adir: ADir) => EitherT(listContents(input, adir).liftM[PhaseResultT])
      for {
        qs <- QueryFile.convertToQScriptRead[Fix, FileSystemErrT[PhaseResultT[Free[S, ?],?],?], QScriptRead[Fix, ?]](lc)(lp).map(shiftRead[Fix])
        _  <- EitherT(WriterT[Free[S, ?], PhaseResults, FileSystemError \/ Unit]((Vector(PhaseResult.tree("QScript (Spark)", qs)), ().right[FileSystemError]).point[Free[S, ?]]))
      } yield qs
    }

    new (QueryFile ~> Free[S, ?]) {
      def apply[A](qf: QueryFile[A]) = qf match {
        case FileExists(f) => fileExists(input, f)
        case ListContents(dir) => listContents(input, dir)
        case QueryFile.ExecutePlan(lp: Fix[LogicalPlan], out: AFile) => {

          val qs = toQScript(lp) >>=
          (qs => EitherT(WriterT(executePlan(input, qs, out, lp).map(_.run.run))))

          qs.run.run
        }
        case QueryFile.EvaluatePlan(lp: Fix[LogicalPlan]) => {
          val qs = toQScript(lp) >>=
          (qs => EitherT(WriterT(evaluatePlan(input, qs, lp).map(_.run.run))))

          qs.run.run
        }
        case QueryFile.More(h) => more(h, input.readChunkSize())
        case QueryFile.Close(h) => close(h)
        case _ => ???
      }
    }}

  implicit def composedFunctor[F[_]: Functor, G[_]: Functor]:
      Functor[(F ∘ G)#λ] =<commit_msg>Simplify joins in sparkcore to EquiJoin<commit_after>/*
 * Copyright 2014–2016 SlamData Inc.
 *
 * Licensed 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 quasar.physical.sparkcore.fs

import quasar.Predef._
import quasar.{Data, LogicalPlan, PhaseResult, PhaseResults, PhaseResultT, PlannerErrT}
import quasar.Planner._
import quasar.contrib.matryoshka._
import quasar.contrib.pathy._
import quasar.effect.{KeyValueStore, MonotonicSeq, Read}
import quasar.fp._
import quasar.fp.eitherT._
import quasar.fp.free._
import quasar.fs._, FileSystemError._, QueryFile._
import quasar.qscript._

import org.apache.spark._
import org.apache.spark.rdd._
import matryoshka._, Recursive.ops._, FunctorT.ops._
import scalaz._, Scalaz._
import scalaz.concurrent.Task

object queryfile {

  type SparkQScript[A] = (QScriptCore[Fix, ?] :\: EquiJoin[Fix, ?] :/: Const[ShiftedRead, ?])#M[A]

  implicit val sparkQScriptToQSTotal
      : Injectable.Aux[SparkQScript, QScriptTotal[Fix, ?]] =
    ::\::[QScriptCore[Fix, ?]](::/::[Fix, EquiJoin[Fix, ?], Const[ShiftedRead, ?]])

  final case class Input(
    fromFile: (SparkContext, AFile) => Task[RDD[String]],
    store: (RDD[Data], AFile) => Task[Unit],
    fileExists: AFile => Task[Boolean],
    listContents: ADir => EitherT[Task, FileSystemError, Set[PathSegment]],
    readChunkSize: () => Int
  )

  type SparkContextRead[A] = Read[SparkContext, A]

  def chrooted[S[_]](input: Input, prefix: ADir)(implicit
    s0: Task :<: S,
    s1: SparkContextRead :<: S,
    s2: MonotonicSeq :<: S,
    s3: KeyValueStore[ResultHandle, RddState, ?] :<: S
  ): QueryFile ~> Free[S, ?] =
    flatMapSNT(interpreter(input)) compose chroot.queryFile[QueryFile](prefix)

  def interpreter[S[_]](input: Input)(implicit
    s0: Task :<: S,
    s1: SparkContextRead :<: S,
    s2: MonotonicSeq :<: S,
    s3: KeyValueStore[ResultHandle, RddState, ?] :<: S
  ): QueryFile ~> Free[S, ?] = {

    val optimize = new Optimize[Fix]

    def toQScript(lp: Fix[LogicalPlan]): FileSystemErrT[PhaseResultT[Free[S, ?], ?], Fix[SparkQScript]] = {
      val lc: DiscoverPath.ListContents[FileSystemErrT[PhaseResultT[Free[S, ?],?],?]] =
        (adir: ADir) => EitherT(listContents(input, adir).liftM[PhaseResultT])
      for {
        qs <- QueryFile.convertToQScriptRead[Fix, FileSystemErrT[PhaseResultT[Free[S, ?],?],?], QScriptRead[Fix, ?]](lc)(lp).map(shiftRead[Fix](_).transCata(
          SimplifyJoin[Fix, QScriptShiftRead[Fix, ?], SparkQScript].simplifyJoin(idPrism.reverseGet)))
        _  <- EitherT(WriterT[Free[S, ?], PhaseResults, FileSystemError \/ Unit]((Vector(PhaseResult.tree("QScript (Spark)", qs)), ().right[FileSystemError]).point[Free[S, ?]]))
      } yield qs
    }

    new (QueryFile ~> Free[S, ?]) {
      def apply[A](qf: QueryFile[A]) = qf match {
        case FileExists(f) => fileExists(input, f)
        case ListContents(dir) => listContents(input, dir)
        case QueryFile.ExecutePlan(lp: Fix[LogicalPlan], out: AFile) => {

          val qs = toQScript(lp) >>=
          (qs => EitherT(WriterT(executePlan(input, qs, out, lp).map(_.run.run))))

          qs.run.run
        }
        case QueryFile.EvaluatePlan(lp: Fix[LogicalPlan]) => {
          val qs = toQScript(lp) >>=
          (qs => EitherT(WriterT(evaluatePlan(input, qs, lp).map(_.run.run))))

          qs.run.run
        }
        case QueryFile.More(h) => more(h, input.readChunkSize())
        case QueryFile.Close(h) => close(h)
        case _ => ???
      }
    }}

  implicit def composedFunctor[F[_]: Functor, G[_]: Functor]:
      Functor[(F ∘ G)#λ] =
{'fraction_non_alphanumeric': 0.1483148958065346, 'fraction_numerical': 0.005145356315924878, 'mean_word_length': 3.7553516819571864, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '679779', 'n_tokens_mistral': 2746, 'n_tokens_neox': 2630, 'n_words': 601}