<commit_before>package almhirt.domain.impl

import java.util.{ UUID => JUUID }
import org.joda.time.LocalDateTime
import scalaz.syntax.validation._
import akka.actor._
import akka.pattern._
import almhirt.common._
import almhirt.almvalidation.kit._
import almhirt.almfuture.all._
import almhirt.core.Almhirt
import almhirt.domain.AggregateRootCell
import almhirt.domain._
import almhirt.domain.DomainEvent
import almhirt.messaging.MessagePublisher
import almhirt.common.CanCreateUuidsAndDateTimes
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.ExecutionContext

trait AggregateRootCellTemplate extends AggregateRootCell with AggregateRootCellWithEventValidation { actor: Actor with ActorLogging =>
  import AggregateRootCell._
  import DomainMessages._
  import almhirt.domaineventlog.DomainEventLog._

  type Event <: DomainEvent
  type AR <: AggregateRoot[AR, Event]

  implicit def execContext: ExecutionContext

  protected def domainEventLog: ActorRef

  protected def reportCellState: AggregateRootCellStateSink
  protected def cellStateReportingDelay: FiniteDuration

  protected def publisher: MessagePublisher

  protected implicit def ccuad: CanCreateUuidsAndDateTimes

  def rebuildAggregateRoot(events: Iterable[Event]): DomainValidation[AR]

  protected def getArMsWarnThreshold: Long
  protected def getArTimeout: FiniteDuration
  protected def updateArMsWarnThreshold: Long
  protected def updateArTimeout: FiniteDuration

  private var lastReportingJob: Option[Cancellable] = None

  private def uninitializedState(alreadyInitializing: Boolean, pendingGetRequests: Vector[ActorRef], pendingUpdateRequests: Vector[(ActorRef, UpdateAggregateRoot)]): Receive = {
    case Initialize =>
      context.become(uninitializedState(true, pendingGetRequests, pendingUpdateRequests))
      fetchAR().onComplete(
        fail => self ! InitializedWithFailure(fail),
        succ => self ! Initialized(succ))
    case Initialized(arOpt) =>
      arOpt match {
        case Some(ar) =>
          if (ar.isDeleted) {
            pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootNotFound(managedAggregateRooId))
            pendingUpdateRequests.map(_._1).foreach(_ ! DomainMessages.AggregateRootUpdateFailed(
              managedAggregateRooId,
              NotFoundProblem(s"""Aggregate root "$managedAggregateRooId" has been deleted.""")))
            moveToDeleted
          } else {
            pendingGetRequests.foreach(_ ! DomainMessages.RequestedAggregateRoot(ar))
            if (pendingUpdateRequests.isEmpty) {
              moveToIdleState(None, ar)
            } else {
              moveToUpdateState(None, Some(ar), pendingUpdateRequests)
            }
          }
        case None =>
          pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootNotFound(managedAggregateRooId))
          if (pendingUpdateRequests.isEmpty) {
            moveToDoesNotExist
          } else {
            moveToUpdateState(None, None, pendingUpdateRequests)
          }
      }
    case InitializedWithFailure(problem) =>
      pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootFetchFailed(managedAggregateRooId, problem))
      pendingUpdateRequests.map(_._1).foreach(_ ! DomainMessages.AggregateRootUpdateFailed(managedAggregateRooId, problem))
      log.error(s"""Could not initialize aggregate root "$managedAggregateRooId": ${problem.message}""")
      moveToErrorState(problem)
    case GetManagedAggregateRoot =>
      context.become(uninitializedState(alreadyInitializing, pendingGetRequests :+ sender, pendingUpdateRequests))
      if (!alreadyInitializing)
        self ! Initialize
    case uar: UpdateAggregateRoot =>
      context.become(uninitializedState(alreadyInitializing, pendingGetRequests, pendingUpdateRequests :+ (sender, uar)))
      if (!alreadyInitializing)
        self ! Initialize
    case _: CachedAggregateRootControl =>
      ()
    case ReportCellState =>
      reportCellState(CellStateUninitialized)
  }

  def idleState(ar: AR, idleSince: LocalDateTime): Receive = {
    case GetManagedAggregateRoot =>
      sender ! RequestedAggregateRoot(ar)
    case uar: UpdateAggregateRoot =>
      moveToUpdateState(Some(ar), Some(ar), Vector((sender, uar)))
      self ! UpdateAR
    case cc: CachedAggregateRootControl =>
      cc match {<commit_msg>Fixed a defect that caused updating once to often on transition to updating state<commit_after>package almhirt.domain.impl

import java.util.{ UUID => JUUID }
import org.joda.time.LocalDateTime
import scalaz.syntax.validation._
import akka.actor._
import akka.pattern._
import almhirt.common._
import almhirt.almvalidation.kit._
import almhirt.almfuture.all._
import almhirt.core.Almhirt
import almhirt.domain.AggregateRootCell
import almhirt.domain._
import almhirt.domain.DomainEvent
import almhirt.messaging.MessagePublisher
import almhirt.common.CanCreateUuidsAndDateTimes
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.ExecutionContext

trait AggregateRootCellTemplate extends AggregateRootCell with AggregateRootCellWithEventValidation { actor: Actor with ActorLogging =>
  import AggregateRootCell._
  import DomainMessages._
  import almhirt.domaineventlog.DomainEventLog._

  type Event <: DomainEvent
  type AR <: AggregateRoot[AR, Event]

  implicit def execContext: ExecutionContext

  protected def domainEventLog: ActorRef

  protected def reportCellState: AggregateRootCellStateSink
  protected def cellStateReportingDelay: FiniteDuration

  protected def publisher: MessagePublisher

  protected implicit def ccuad: CanCreateUuidsAndDateTimes

  def rebuildAggregateRoot(events: Iterable[Event]): DomainValidation[AR]

  protected def getArMsWarnThreshold: Long
  protected def getArTimeout: FiniteDuration
  protected def updateArMsWarnThreshold: Long
  protected def updateArTimeout: FiniteDuration

  private var lastReportingJob: Option[Cancellable] = None

  private def uninitializedState(alreadyInitializing: Boolean, pendingGetRequests: Vector[ActorRef], pendingUpdateRequests: Vector[(ActorRef, UpdateAggregateRoot)]): Receive = {
    case Initialize =>
      context.become(uninitializedState(true, pendingGetRequests, pendingUpdateRequests))
      fetchAR().onComplete(
        fail => self ! InitializedWithFailure(fail),
        succ => self ! Initialized(succ))
    case Initialized(arOpt) =>
      arOpt match {
        case Some(ar) =>
          if (ar.isDeleted) {
            pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootNotFound(managedAggregateRooId))
            pendingUpdateRequests.map(_._1).foreach(_ ! DomainMessages.AggregateRootUpdateFailed(
              managedAggregateRooId,
              NotFoundProblem(s"""Aggregate root "$managedAggregateRooId" has been deleted.""")))
            moveToDeleted
          } else {
            pendingGetRequests.foreach(_ ! DomainMessages.RequestedAggregateRoot(ar))
            if (pendingUpdateRequests.isEmpty) {
              moveToIdleState(None, ar)
            } else {
              moveToUpdateState(None, Some(ar), pendingUpdateRequests)
            }
          }
        case None =>
          pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootNotFound(managedAggregateRooId))
          if (pendingUpdateRequests.isEmpty) {
            moveToDoesNotExist
          } else {
            moveToUpdateState(None, None, pendingUpdateRequests)
          }
      }
    case InitializedWithFailure(problem) =>
      pendingGetRequests.foreach(_ ! DomainMessages.AggregateRootFetchFailed(managedAggregateRooId, problem))
      pendingUpdateRequests.map(_._1).foreach(_ ! DomainMessages.AggregateRootUpdateFailed(managedAggregateRooId, problem))
      log.error(s"""Could not initialize aggregate root "$managedAggregateRooId": ${problem.message}""")
      moveToErrorState(problem)
    case GetManagedAggregateRoot =>
      context.become(uninitializedState(alreadyInitializing, pendingGetRequests :+ sender, pendingUpdateRequests))
      if (!alreadyInitializing)
        self ! Initialize
    case uar: UpdateAggregateRoot =>
      context.become(uninitializedState(alreadyInitializing, pendingGetRequests, pendingUpdateRequests :+ (sender, uar)))
      if (!alreadyInitializing)
        self ! Initialize
    case _: CachedAggregateRootControl =>
      ()
    case ReportCellState =>
      reportCellState(CellStateUninitialized)
  }

  def idleState(ar: AR, idleSince: LocalDateTime): Receive = {
    case GetManagedAggregateRoot =>
      sender ! RequestedAggregateRoot(ar)
    case uar: UpdateAggregateRoot =>
      moveToUpdateState(Some(ar), Some(ar), Vector((sender, uar)))
    case cc: CachedAggregateRootControl =>
      cc match {
{'fraction_non_alphanumeric': 0.0774971297359357, 'fraction_numerical': 0.0004592422502870264, 'mean_word_length': 4.115091015854374, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5453908', 'n_tokens_mistral': 2376, 'n_tokens_neox': 2383, 'n_words': 491}