<commit_before>/*
 * 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.
 *
 * Contributors:
 *     <NAME> <<EMAIL>>
 */

package com.thenetcircle.event_bus.tasks.kafka

import akka.kafka.ConsumerMessage.CommittableOffset
import akka.kafka.scaladsl.Consumer
import akka.kafka.{AutoSubscription, ConsumerSettings, Subscriptions}
import akka.stream.scaladsl.{Flow, Keep, Sink}
import akka.util.ByteString
import akka.{Done, NotUsed}
import com.thenetcircle.event_bus.event.Event
import com.thenetcircle.event_bus.event.extractor.EventExtractorFactory
import com.thenetcircle.event_bus.interface.{SourceTask, SourceTaskBuilder}
import com.thenetcircle.event_bus.misc.ConfigStringParser
import com.thenetcircle.event_bus.story.TaskRunningContext
import com.thenetcircle.event_bus.tasks.kafka.extended.KafkaKeyDeserializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.StrictLogging
import org.apache.kafka.common.serialization.ByteArrayDeserializer
import net.ceedubs.ficus.Ficus._

import scala.concurrent.Future
import scala.concurrent.duration._

class KafkaSource(val settings: KafkaSourceSettings) extends SourceTask with StrictLogging {

  require(settings.bootstrapServers.isEmpty, "bootstrap servers is required.")
  require(settings.groupId.isEmpty, "group id is required.")

  def getSubscription(): AutoSubscription =
    if (settings.subscribedTopics.isLeft) {
      Subscriptions.topics(settings.subscribedTopics.left.get)
    } else {
      Subscriptions.topicPattern(settings.subscribedTopics.right.get)
    }

  def getConsumerSettings()(
      implicit context: TaskRunningContext
  ): ConsumerSettings[ConsumerKey, ConsumerValue] = {
    var _consumerSettings = ConsumerSettings[ConsumerKey, ConsumerValue](
      context.getEnvironment().getConfig(),
      new KafkaKeyDeserializer,
      new ByteArrayDeserializer
    )

    settings.properties.foreach {
      case (_key, _value) => _consumerSettings = _consumerSettings.withProperty(_key, _value)
    }

    _consumerSettings
      .withBootstrapServers(settings.bootstrapServers)
      .withGroupId(settings.groupId)
      .withCommitTimeout(settings.commitTimeout)
      .withProperty("enable.auto.commit", "false")
      .withProperty("client.id", "eventbus-kafkasource")
  }

  override def runWith(
      handler: Flow[Event, Future[Event], NotUsed]
  )(implicit context: TaskRunningContext): Future[Done] = {
    Consumer
      .committablePartitionedSource(getConsumerSettings(), getSubscription())
      .map {
        case (topicPartition, source) =>
          source
            .mapAsync(1)(message => {
              val eventExtractor = message.record
                .key()
                .data
                .map(_key => EventExtractorFactory.getExtractor(_key.eventFormat))
                .getOrElse(EventExtractorFactory.defaultExtractor)

              eventExtractor
                .extract(ByteString(message.record.value()), Some(message.committableOffset))
            })
            // .withAttributes(supervisionStrategy(resumingDecider))
            .via(handler)
            .mapAsync(1)(_.flatMap(event => {
              event.getPassThrough[CommittableOffset] match {
                case Some(offset) => offset.commitScaladsl()
                case None =>
                  throw new Exception("event passthrough is missed")
              }
            }))
            .toMat(Sink.ignore)(Keep.right)
            .run()
      }
      .mapAsyncUnordered(settings.maxConcurrentPartitions)(identity)
      .runWith(Sink.ignore)
  }
}

case class KafkaSourceSettings(bootstrapServers: String,
                               groupId: String,
                               subscribedTopics: Either[Set[String], String],
                               maxConcurrentPartitions: Int = 100,
                               properties: Map[String, String] = Map.empty,
                               commitTimeout: FiniteDuration = 15.seconds)

class KafkaSourceBuilder() extends SourceTaskBuilder {

  override def build(configString: String): KafkaSource = {

    val defaultConfig: Config = ConfigStringParser.convertStringToConfig(
      """
      |{
      |  # "bootstrap-servers": "...",
      |  # "group-id": "...",
      |  # "topics": [],<commit_msg>small changes<commit_after>/*
 * 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.
 *
 * Contributors:
 *     <NAME> <<EMAIL>>
 */

package com.thenetcircle.event_bus.tasks.kafka

import akka.kafka.ConsumerMessage.CommittableOffset
import akka.kafka.scaladsl.Consumer
import akka.kafka.{AutoSubscription, ConsumerSettings, Subscriptions}
import akka.stream.scaladsl.{Flow, Keep, Sink}
import akka.util.ByteString
import akka.{Done, NotUsed}
import com.thenetcircle.event_bus.event.Event
import com.thenetcircle.event_bus.event.extractor.EventExtractorFactory
import com.thenetcircle.event_bus.interface.{SourceTask, SourceTaskBuilder}
import com.thenetcircle.event_bus.misc.ConfigStringParser
import com.thenetcircle.event_bus.story.TaskRunningContext
import com.thenetcircle.event_bus.tasks.kafka.extended.KafkaKeyDeserializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.StrictLogging
import org.apache.kafka.common.serialization.ByteArrayDeserializer
import net.ceedubs.ficus.Ficus._

import scala.concurrent.Future
import scala.concurrent.duration._

class KafkaSource(val settings: KafkaSourceSettings) extends SourceTask with StrictLogging {

  require(settings.bootstrapServers.isEmpty, "bootstrap servers is required.")
  require(settings.groupId.isEmpty, "group id is required.")

  def getSubscription(): AutoSubscription =
    if (settings.subscribedTopics.isLeft) {
      Subscriptions.topics(settings.subscribedTopics.left.get)
    } else {
      Subscriptions.topicPattern(settings.subscribedTopics.right.get)
    }

  def getConsumerSettings()(
      implicit context: TaskRunningContext
  ): ConsumerSettings[ConsumerKey, ConsumerValue] = {
    var _consumerSettings = ConsumerSettings[ConsumerKey, ConsumerValue](
      context.getEnvironment().getConfig(),
      new KafkaKeyDeserializer,
      new ByteArrayDeserializer
    )

    settings.properties.foreach {
      case (_key, _value) => _consumerSettings = _consumerSettings.withProperty(_key, _value)
    }

    _consumerSettings
      .withBootstrapServers(settings.bootstrapServers)
      .withGroupId(settings.groupId)
      .withCommitTimeout(settings.commitTimeout)
      .withProperty("enable.auto.commit", "false")
      .withProperty("client.id", "eventbus-kafkasource")
  }

  override def runWith(
      handler: Flow[Event, Future[Event], NotUsed]
  )(implicit context: TaskRunningContext): Future[Done] = {
    Consumer
      .committablePartitionedSource(getConsumerSettings(), getSubscription())
      .map {
        case (topicPartition, source) =>
          source
            .mapAsync(1)(message => {
              val eventExtractor = message.record
                .key()
                .data
                .map(_key => EventExtractorFactory.getExtractor(_key.eventFormat))
                .getOrElse(EventExtractorFactory.defaultExtractor)

              eventExtractor
                .extract(ByteString(message.record.value()), Some(message.committableOffset))
            })
            // .withAttributes(supervisionStrategy(resumingDecider))
            .via(handler)
            .mapAsync(1)(_.flatMap(event => {
              event.getPassThrough[CommittableOffset] match {
                case Some(offset) => offset.commitScaladsl()
                case None =>
                  throw new Exception("event passthrough is missed")
              }
            }))
            .toMat(Sink.ignore)(Keep.right)
            .run()
      }
      .mapAsyncUnordered(settings.maxConcurrentPartitions)(identity)
      .runWith(Sink.ignore)
  }
}

// TODO: change the consumer offset
case class KafkaSourceSettings(bootstrapServers: String,
                               groupId: String,
                               subscribedTopics: Either[Set[String], String],
                               maxConcurrentPartitions: Int = 100,
                               properties: Map[String, String] = Map.empty,
                               commitTimeout: FiniteDuration = 15.seconds)

class KafkaSourceBuilder() extends SourceTaskBuilder {

  override def build(configString: String): KafkaSource = {

    val defaultConfig: Config = ConfigStringParser.convertStringToConfig(
      """
      |{
      |  # "bootstrap-servers": "...",
      |  # "group-id": "...",
      |  # "topics": [],
{'fraction_non_alphanumeric': 0.09609766277128548, 'fraction_numerical': 0.002295492487479132, 'mean_word_length': 3.027310924369748, 'pattern_counts': {'":': 6, '<': 9, '<?xml version=': 0, '>': 23, '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': '4047267', 'n_tokens_mistral': 2638, 'n_tokens_neox': 2563, 'n_words': 544}