Quick commit before delving into python stuff. See you later.
[aquarium] / src / main / scala / gr / grnet / aquarium / actor / service / user / UserActor.scala
index 95d04fe..d7604cc 100644 (file)
@@ -37,21 +37,27 @@ package gr.grnet.aquarium.actor
 package service
 package user
 
-import gr.grnet.aquarium.actor._
-
-import akka.config.Supervision.Temporary
-import gr.grnet.aquarium.actor.message.event.{ProcessResourceEvent, ProcessIMEvent}
-import gr.grnet.aquarium.actor.message.config.{InitializeUserState, ActorProviderConfigured, AquariumPropertiesLoaded}
+import gr.grnet.aquarium.{Real, AquariumInternalError}
+import gr.grnet.aquarium.actor.message.GetUserBalanceRequest
+import gr.grnet.aquarium.actor.message.GetUserBalanceResponse
+import gr.grnet.aquarium.actor.message.GetUserBalanceResponseData
+import gr.grnet.aquarium.actor.message.GetUserBillRequest
+import gr.grnet.aquarium.actor.message.GetUserBillResponse
+import gr.grnet.aquarium.actor.message.GetUserBillResponseData
+import gr.grnet.aquarium.actor.message.GetUserStateRequest
+import gr.grnet.aquarium.actor.message.GetUserStateResponse
+import gr.grnet.aquarium.actor.message.GetUserWalletRequest
+import gr.grnet.aquarium.actor.message.GetUserWalletResponse
+import gr.grnet.aquarium.actor.message.GetUserWalletResponseData
+import gr.grnet.aquarium.actor.message.config.AquariumPropertiesLoaded
+import gr.grnet.aquarium.charging.state.UserStateModel
+import gr.grnet.aquarium.message.avro.gen.{UserAgreementHistoryMsg, IMEventMsg, ResourceEventMsg}
+import gr.grnet.aquarium.message.avro.{ModelFactory, MessageFactory, MessageHelpers}
+import gr.grnet.aquarium.service.event.BalanceEvent
 import gr.grnet.aquarium.util.date.TimeHelpers
-import gr.grnet.aquarium.event.model.im.IMEventModel
-import gr.grnet.aquarium.actor.message.{GetUserStateResponse, GetUserBalanceResponseData, GetUserBalanceResponse, GetUserStateRequest, GetUserBalanceRequest}
-import gr.grnet.aquarium.util.{LogHelpers, shortClassNameOf, shortNameOfClass, shortNameOfType}
-import gr.grnet.aquarium.computation.reason.{RealtimeBillingCalculation, InitialUserActorSetup, UserStateChangeReason, IMEventArrival, InitialUserStateSetup}
-import gr.grnet.aquarium.{AquariumInternalError, Aquarium}
-import gr.grnet.aquarium.computation.state.parts.IMStateSnapshot
-import gr.grnet.aquarium.computation.BillingMonthInfo
-import gr.grnet.aquarium.computation.state.{UserStateBootstrap, UserState}
-import gr.grnet.aquarium.event.model.resource.ResourceEventModel
+import gr.grnet.aquarium.util.{LogHelpers, shortClassNameOf}
+import gr.grnet.aquarium.policy.{ResourceType, PolicyModel}
+import gr.grnet.aquarium.charging.bill.BillEntryMsg
 
 /**
  *
@@ -59,349 +65,370 @@ import gr.grnet.aquarium.event.model.resource.ResourceEventModel
  */
 
 class UserActor extends ReflectiveRoleableActor {
-  private[this] var _userID: String = "<?>"
-  private[this] var _imState: IMStateSnapshot = _
-  private[this] var _userState: UserState = _
-  private[this] var _latestResourceEventOccurredMillis = TimeHelpers.nowMillis() // some valid datetime
+  private[this] var _imMsgCount = 0
+  private[this] var _userStateModel: UserStateModel = _
+
+  def userID = {
+    if(!haveUserState) {
+      throw new AquariumInternalError("%s not initialized")
+    }
 
-  self.lifeCycle = Temporary
+    this._userStateModel.userID
+  }
+
+  override def postStop() {
+    DEBUG("I am finally stopped (in postStop())")
+    aquarium.akkaService.notifyUserActorPostStop(this)
+  }
 
-  private[this] def _shutmedown(): Unit = {
+  private[this] def shutmedown(): Unit = {
     if(haveUserState) {
-      UserActorCache.invalidate(_userID)
+      aquarium.akkaService.invalidateUserActor(this)
     }
-
-    self.stop()
   }
 
   override protected def onThrowable(t: Throwable, message: AnyRef) = {
     LogHelpers.logChainOfCauses(logger, t)
     ERROR(t, "Terminating due to: %s(%s)", shortClassNameOf(t), t.getMessage)
 
-    _shutmedown()
+    shutmedown()
   }
 
   def role = UserActorRole
 
-  private[this] def aquarium: Aquarium = Aquarium.Instance
-
-  private[this] def userStateComputations = aquarium.userStateComputations
+  private[this] def chargingService = aquarium.chargingService
 
-  private[this] def stdUserStateStoreFunc = (userState: UserState) ⇒ {
-    aquarium.userStateStore.insertUserState(userState)
+  def onAquariumPropertiesLoaded(event: AquariumPropertiesLoaded): Unit = {
   }
 
-  private[this] def _timestampTheshold = {
-    aquarium.props.getLong(Aquarium.Keys.user_state_timestamp_threshold).getOr(1000L * 60 * 5 /* 5 minutes */)
+  private[this] def unsafeUserCreationIMEventMsg = {
+    this._userStateModel.unsafeUserCreationIMEvent
   }
 
-  private[this] def haveUserState = {
-    this._userState ne null
+  private[this] def haveAgreements = {
+    (this._userStateModel ne null)
   }
 
-  private[this] def haveIMState = {
-    this._imState ne null
+  private[this] def haveUserCreationEvent = {
+    haveAgreements &&
+    this._userStateModel.hasUserCreationEvent
   }
 
-  def onAquariumPropertiesLoaded(event: AquariumPropertiesLoaded): Unit = {
-  }
-
-  def onActorProviderConfigured(event: ActorProviderConfigured): Unit = {
+  private[this] def haveUserState = {
+    (this._userStateModel ne null)
   }
 
-  private[this] def _updateIMStateRoleHistory(imEvent: IMEventModel, roleCheck: Option[String]) = {
-    if(haveIMState) {
-      val (newState,
-           creationTimeChanged,
-           activationTimeChanged,
-           roleChanged) = this._imState.updatedWithEvent(imEvent, roleCheck)
-
-      this._imState = newState
-      (creationTimeChanged, activationTimeChanged, roleChanged)
-    } else {
-      this._imState = IMStateSnapshot.initial(imEvent)
-      (
-        imEvent.isCreateUser,
-        true, // first activation status is a change by default??
-        true  // first role is a change by default??
-        )
-    }
-  }
+  private[this] def isInitial = this._userStateModel.isInitial
 
   /**
-   * Creates the IMStateSnapshot and returns the number of updates it made to it.
+   * Creates the agreement history from all the stored IMEvents.
+   *
+   * @return (`true` iff there was a user CREATE event, the number of events processed)
    */
-  private[this] def createInitialIMState(): Unit = {
-    val store = aquarium.imEventStore
+  private[this] def createUserAgreementHistoryFromIMEvents(userID: String): (Boolean, Int) = {
+    DEBUG("createUserAgreementHistoryFromStoredIMEvents()")
+    assert(haveUserState, "haveUserState")
 
-    var _roleCheck = None: Option[String]
 
-    // this._userID is already set up
-    store.replayIMEventsInOccurrenceOrder(this._userID) { imEvent ⇒
-      DEBUG("Replaying %s", imEvent)
+    var _imcounter = 0
 
-      val (creationTimeChanged, activationTimeChanged, roleChanged) = _updateIMStateRoleHistory(imEvent, _roleCheck)
-      _roleCheck = this._imState.roleHistory.lastRoleName
+    val hadCreateEvent = aquarium.imEventStore.foreachIMEventInOccurrenceOrder(userID) { imEvent ⇒
+      _imcounter += 1
+      DEBUG("Replaying [%s/%s] %s", shortClassNameOf(imEvent), _imcounter, imEvent)
 
-      DEBUG(
-        "(creationTimeChanged, activationTimeChanged, roleChanged)=(%s, %s, %s) using %s",
-        creationTimeChanged, activationTimeChanged, roleChanged,
-        imEvent
-      )
+      if(_imcounter == 1 && !MessageHelpers.isUserCreationIMEvent(imEvent)) {
+        // The very first event must be a CREATE event. Otherwise we abort initialization.
+        // This will normally happen during devops :)
+        INFO("Ignoring first %s since it is not CREATE", shortClassNameOf(imEvent))
+        false
+      }
+      else {
+        val effectiveFromMillis = imEvent.getOccurredMillis
+        val role = imEvent.getRole
+        // calling unsafe just for the side-effect
+        assert(
+          aquarium.unsafeFullPriceTableForRoleAt(role, effectiveFromMillis) ne null,
+          "aquarium.unsafeFullPriceTableForRoleAt(%s, %s) ne null".format(role, effectiveFromMillis)
+        )
+
+        this._userStateModel.insertUserAgreementMsgFromIMEvent(imEvent)
+        true
+      }
     }
 
-    DEBUG("New %s = %s", shortNameOfType[IMStateSnapshot], this._imState)
-  }
+    this._imMsgCount = _imcounter
 
-  /**
-   * Resource events are processed only if the user has been activated.
-   */
-  private[this] def shouldProcessResourceEvents: Boolean = {
-    haveIMState && this._imState.hasBeenCreated
+    DEBUG("Agreements: %s", this._userStateModel.userAgreementHistoryMsg)
+    (hadCreateEvent, _imcounter)
   }
 
-  private[this] def loadUserStateAndUpdateRoleHistory(): Unit = {
-    val userCreationMillis = this._imState.userCreationMillis.get
-    val initialRole = this._imState.roleHistory.firstRole.get.name
-
-    val userStateBootstrap = UserStateBootstrap(
-      this._userID,
-      userCreationMillis,
-      initialRole,
-      aquarium.initialAgreementForRole(initialRole, userCreationMillis),
-      aquarium.initialBalanceForRole(initialRole, userCreationMillis)
+  private[this] def saveFirstUserState(userID: String) {
+    this._userStateModel.userStateMsg.setIsFirst(true)
+    this._userStateModel.updateUserStateMsg(
+      aquarium.userStateStore.insertUserState(this._userStateModel.userStateMsg)
     )
+  }
 
-    val now = TimeHelpers.nowMillis()
-    val userState = userStateComputations.doMonthBillingUpTo(
-      BillingMonthInfo.fromMillis(now),
-      now,
-      userStateBootstrap,
-      aquarium.currentResourcesMap,
-      InitialUserActorSetup(),
-      stdUserStateStoreFunc,
-      None
+  private[this] def saveSubsequentUserState() {
+    this._userStateModel.userStateMsg.setIsFirst(false)
+    this._userStateModel.updateUserStateMsg(
+      aquarium.userStateStore.insertUserState(this._userStateModel.userStateMsg)
     )
+  }
 
-    this._userState = userState
+  private[this] def loadLastKnownUserStateAndUpdateAgreements() {
+    val userID = this._userStateModel.userID
+    aquarium.userStateStore.findLatestUserState(userID) match {
+      case None ⇒
+        // First user state ever
+        saveFirstUserState(userID)
 
-    // Final touch: Update role history
-    if(haveIMState && haveUserState) {
-      if(this._userState.roleHistory != this._imState.roleHistory) {
-        this._userState = newUserStateWithUpdatedRoleHistory(InitialUserActorSetup())
-      }
+      case Some(latestUserState) ⇒
+        this._userStateModel.updateUserStateMsg(latestUserState)
     }
   }
 
-  private[this] def createInitialUserState(event: InitializeUserState): Unit = {
-    if(!haveIMState) {
-      // Should have been created from `createIMState()`
-      DEBUG("Cannot create user state from %s, since %s = %s", event, shortNameOfClass(classOf[IMStateSnapshot]), this._imState)
-      return
-    }
+  private[this] def processResourceEventsAfterLastKnownUserState() {
+    // Update the user state snapshot with fresh (ie not previously processed) events.
+    aquarium.resourceEventStore.foreachResourceEventOccurredInPeriod(
+      this._userStateModel.userID,
+      this._userStateModel.latestResourceEventOccurredMillis,
+      TimeHelpers.nowMillis()
+    )
+  }
 
-    if(!this._imState.hasBeenCreated) {
-      // Cannot set the initial state!
-      DEBUG("Cannot create %s from %s, since user has not been created", shortNameOfType[UserState], event)
-      return
+  private[this] def makeUserStateMsgUpToDate() {
+    loadLastKnownUserStateAndUpdateAgreements()
+    processResourceEventsAfterLastKnownUserState()
+  }
+
+  private[this] def checkInitial(nextThing: () ⇒ Any = () ⇒ {}): Boolean = {
+    if(!isInitial) {
+      return false
     }
 
-    // We will also need this functionality when receiving IMEvents,
-    // so we place it in a method
-    loadUserStateAndUpdateRoleHistory()
+    val (userCreated, imEventsCount) = createUserAgreementHistoryFromIMEvents(userID)
 
-    if(haveUserState) {
-      DEBUG("%s = %s", shortNameOfType[UserState], this._userState)
+    if(userCreated) {
+      makeUserStateMsgUpToDate()
     }
-  }
 
-  def onInitializeUserState(event: InitializeUserState): Unit = {
-    this._userID = event.userID
-    DEBUG("Got %s", event)
+    nextThing()
 
-    createInitialIMState()
-    createInitialUserState(event)
+    true
   }
 
   /**
-   * Creates a new user state, taking into account the latest role history in IM state snapshot.
-   * Having an IM state snapshot is a prerequisite, otherwise you get an exception; so check before you
-   * call this.
+   * Processes [[gr.grnet.aquarium.message.avro.gen.IMEventMsg]]s that come directly from the
+   * messaging hub (rabbitmq).
    */
-  private[this] def newUserStateWithUpdatedRoleHistory(stateChangeReason: UserStateChangeReason): UserState = {
-    // FIXME: Also update agreement
-    this._userState.newWithRoleHistory(this._imState.roleHistory, stateChangeReason)
-  }
+  def onIMEventMsg(imEvent: IMEventMsg) {
+    if(checkInitial()) {
+      return
+    }
 
-  /**
-   * Process [[gr.grnet.aquarium.event.model.im.IMEventModel]]s.
-   * When this method is called, we assume that all proper checks have been made and it
-   * is OK to proceed with the event processing.
-   */
-  def onProcessIMEvent(processEvent: ProcessIMEvent): Unit = {
-    val imEvent = processEvent.imEvent
+    // Check for out of sync (regarding IMEvents)
+    val isOutOfSyncIM = imEvent.getOccurredMillis < this._userStateModel.latestIMEventOccurredMillis
+    if(isOutOfSyncIM) {
+      // clear all resource state
+      // FIXME implement
 
-    if(!haveIMState) {
-      // This is an error. Should have been initialized from somewhere ...
-      throw new AquariumInternalError("Got %s while uninitialized".format(processEvent))
+      return
     }
 
-    if(this._imState.latestIMEvent.id == imEvent.id) {
-      // This happens when the actor is brought to life, then immediately initialized, and then
-      // sent the first IM event. But from the initialization procedure, this IM event will have
-      // already been loaded from DB!
-      INFO("Ignoring first %s just after %s birth", imEvent.toDebugString, shortClassNameOf(this))
-      logSeparator()
+    // Check out of sync (regarding ResourceEvents)
+    val isOutOfSyncRC = false // FIXME implement
+    if(isOutOfSyncRC) {
+      // TODO
 
       return
     }
 
-    val (creationTimeChanged,
-         activationTimeChanged,
-         roleChanged) = _updateIMStateRoleHistory(imEvent, this._imState.roleHistory.lastRoleName)
+    // Make new agreement
+    this._userStateModel.insertUserAgreementMsgFromIMEvent(imEvent)
+    this._imMsgCount += 1
 
-    DEBUG(
-      "(creationTimeChanged, activationTimeChanged, roleChanged)=(%s, %s, %s) using %s",
-      creationTimeChanged, activationTimeChanged, roleChanged,
-      imEvent
-    )
-
-    // Must also update user state if we know when in history the life of a user begins
-    if(creationTimeChanged) {
-      if(!haveUserState) {
-        loadUserStateAndUpdateRoleHistory()
-        INFO("Loaded %s due to %s", shortNameOfType[UserState], imEvent)
-      } else {
-        // Just update role history
-        this._userState = newUserStateWithUpdatedRoleHistory(IMEventArrival(imEvent))
-        INFO("Updated %s due to %s", shortNameOfType[UserState], imEvent)
-      }
+    if(MessageHelpers.isUserCreationIMEvent(imEvent)) {
+      makeUserStateMsgUpToDate()
     }
 
-    DEBUG("New %s = %s", shortNameOfType[IMStateSnapshot], this._imState)
-    logSeparator()
+    DEBUG("Agreements: %s", this._userStateModel.userAgreementHistoryMsg)
   }
 
-  def onProcessResourceEvent(event: ProcessResourceEvent): Unit = {
-    val rcEvent = event.rcEvent
+  def onResourceEventMsg(rcEvent: ResourceEventMsg) {
+    if(checkInitial()) {
+      return
+    }
 
-    if(!shouldProcessResourceEvents) {
-      // This means the user has not been activated. So, we do not process any resource event
-      DEBUG("Not processing %s", rcEvent.toJsonString)
-      logSeparator()
+    if(!haveUserCreationEvent) {
+      DEBUG("No agreements. Ignoring %s", rcEvent)
 
       return
     }
 
-    this._userState.findLatestResourceEventID match {
-      case Some(id) ⇒
-        if(id == rcEvent.id) {
-          INFO("Ignoring first %s just after %s birth", rcEvent.toDebugString, shortClassNameOf(this))
-          logSeparator()
-
-          return
-        }
+    assert(haveUserState, "haveUserState")
 
-      case _ ⇒
-    }
+    val oldTotalCredits = this._userStateModel.totalCreditsAsReal
 
-    val now = TimeHelpers.nowMillis()
-    val dt  = now - this._latestResourceEventOccurredMillis
-    val belowThreshold = dt <= _timestampTheshold
+    chargingService.processResourceEvent(
+      rcEvent.getReceivedMillis,
+      rcEvent,
+      this._userStateModel,
+      aquarium.currentResourceMapping,
+      true
+    )
 
-    if(belowThreshold) {
-      this._latestResourceEventOccurredMillis = event.rcEvent.occurredMillis
+    val newTotalCredits = this._userStateModel.totalCreditsAsReal
 
-      DEBUG("Below threshold (%s ms). Not processing %s", this._timestampTheshold, rcEvent.toJsonString)
-      return
+    if(oldTotalCredits.signum * newTotalCredits.signum < 0) {
+      aquarium.eventBus ! new BalanceEvent(userID, newTotalCredits >= 0)
     }
 
-    val userID = this._userID
-    val userCreationMillis = this._imState.userCreationMillis.get
-    val initialRole = this._imState.roleHistory.firstRoleName.getOrElse(aquarium.defaultInitialUserRole)
-    val initialAgreement = aquarium.initialAgreementForRole(initialRole, userCreationMillis)
-    val initialCredits   = aquarium.initialBalanceForRole(initialRole, userCreationMillis)
-    val userStateBootstrap = UserStateBootstrap(
-      userID,
-      userCreationMillis,
-      initialRole,
-      initialAgreement,
-      initialCredits
-    )
-    val billingMonthInfo = BillingMonthInfo.fromMillis(now)
-    val currentResourcesMap = aquarium.currentResourcesMap
-    val calculationReason = RealtimeBillingCalculation(None, now)
-    val eventOccurredMillis = rcEvent.occurredMillis
-
-    DEBUG("Using %s", currentResourcesMap)
-
-    this._userState = aquarium.userStateComputations.doMonthBillingUpTo(
-      billingMonthInfo,
-      now max eventOccurredMillis, // take into account that the event may be out-of-sync
-      userStateBootstrap,
-      currentResourcesMap,
-      calculationReason,
-      stdUserStateStoreFunc
-    )
-
-    this._latestResourceEventOccurredMillis = event.rcEvent.occurredMillis
+    DEBUG("Updated %s", this._userStateModel)
+  }
 
-    DEBUG("New %s = %s", shortClassNameOf(this._userState), this._userState)
+  def onGetUserBillRequest(event: GetUserBillRequest): Unit = {
+    checkInitial()
+
+    try{
+      val timeslot = event.timeslot
+      val resourceTypes: Map[String, ResourceType] = aquarium.policyStore.
+                          loadSortedPolicyModelsWithin(timeslot.from.getTime,
+                                                       timeslot.to.getTime).
+                          values.headOption match {
+          case None => Map[String,ResourceType]()
+          case Some(policy:PolicyModel) => policy.resourceTypesMap
+      }
+      val state= if(haveUserState) Some(this._userStateModel.userStateMsg) else None
+      val billEntryMsg = BillEntryMsg.fromWorkingUserState(timeslot,this.userID,state,resourceTypes)
+      //val billEntryMsg = MessageFactory.createBillEntryMsg(billEntry)
+      //logger.debug("BILL ENTRY MSG: " + billEntryMsg.toString)
+      val billData = GetUserBillResponseData(this.userID,billEntryMsg)
+      sender ! GetUserBillResponse(Right(billData))
+    } catch {
+      case e:Exception =>
+        e.printStackTrace()
+        sender ! GetUserBillResponse(Left("Internal Server Error [AQU-BILL-0001]"), 500)
+    }
   }
 
   def onGetUserBalanceRequest(event: GetUserBalanceRequest): Unit = {
+    checkInitial()
+
     val userID = event.userID
 
-    (haveIMState, haveUserState) match {
+    (haveAgreements, haveUserState) match {
       case (true, true) ⇒
-        // (have IMState, have UserState)
-        this._imState.hasBeenActivated match {
-          case true ⇒
-            // (have IMState, activated, have UserState)
-            self reply GetUserBalanceResponse(Right(GetUserBalanceResponseData(userID, this._userState.totalCredits)))
+        // (User CREATEd, with balance state)
+        val realtimeMillis = TimeHelpers.nowMillis()
+        chargingService.calculateRealtimeUserState(
+          this._userStateModel,
+          aquarium.currentResourceMapping,
+          realtimeMillis
+        )
 
-          case false ⇒
-            // (have IMState, not activated, have UserState)
-            // Since we have user state, we should have been activated
-            self reply GetUserBalanceResponse(Left("Internal Server Error [AQU-BAL-0001]"), 500)
-        }
+        sender ! GetUserBalanceResponse(Right(GetUserBalanceResponseData(this.userID, this._userStateModel.totalCredits)))
 
       case (true, false) ⇒
-        // (have IMState, no UserState)
-        this._imState.hasBeenActivated match {
-          case true  ⇒
-            // (have IMState, activated, no UserState)
-            // Since we are activated, we should have some state.
-            self reply GetUserBalanceResponse(Left("Internal Server Error [AQU-BAL-0002]"), 500)
-          case false ⇒
-            // (have IMState, not activated, no UserState)
-            // The user is virtually unknown
-            self reply GetUserBalanceResponse(Left("User %s not activated [AQU-BAL-0003]".format(userID)), 404 /*Not found*/)
-        }
+        // (User CREATEd, no balance state)
+        // Return the default initial balance
+        sender ! GetUserBalanceResponse(
+          Right(
+            GetUserBalanceResponseData(
+              this.userID,
+              aquarium.initialUserBalance(this.unsafeUserCreationIMEventMsg.getRole, this.unsafeUserCreationIMEventMsg.getOccurredMillis).toString()
+            )))
 
       case (false, true) ⇒
-        // (no IMState, have UserState)
-        // A bit ridiculous situation
-        self reply GetUserBalanceResponse(Left("Unknown user %s [AQU-BAL-0004]".format(userID)), 404/*Not found*/)
+        // (Not CREATEd, with balance state)
+        // Clearly this is internal error
+        sender ! GetUserBalanceResponse(Left("Internal Server Error [AQU-BAL-0001]"), 500)
 
       case (false, false) ⇒
-        // (no IMState, no UserState)
-        self reply GetUserBalanceResponse(Left("Unknown user %s [AQU-BAL-0005]".format(userID)), 404/*Not found*/)
+        // (Not CREATEd, no balance state)
+        // The user is completely unknown
+        sender ! GetUserBalanceResponse(Left("Unknown user %s [AQU-BAL-0004]".format(userID)), 404/*Not found*/)
     }
   }
 
   def onGetUserStateRequest(event: GetUserStateRequest): Unit = {
+    checkInitial()
+
     haveUserState match {
       case true ⇒
-        self reply GetUserStateResponse(Right(this._userState))
+        val realtimeMillis = TimeHelpers.nowMillis()
+        chargingService.calculateRealtimeUserState(
+          this._userStateModel,
+          aquarium.currentResourceMapping,
+          realtimeMillis
+        )
+
+        sender ! GetUserStateResponse(Right(this._userStateModel.userStateMsg))
+
+      case false ⇒
+        sender ! GetUserStateResponse(Left("No state for user %s [AQU-STA-0006]".format(event.userID)), 404)
+    }
+  }
+
+  def onGetUserWalletRequest(event: GetUserWalletRequest): Unit = {
+    checkInitial()
+
+    haveUserState match {
+      case true ⇒
+        DEBUG("haveWorkingUserState: %s", event)
+        val realtimeMillis = TimeHelpers.nowMillis()
+        chargingService.calculateRealtimeUserState(
+          this._userStateModel,
+          aquarium.currentResourceMapping,
+          realtimeMillis
+        )
+
+        sender ! GetUserWalletResponse(
+          Right(
+            GetUserWalletResponseData(
+              this.userID,
+              this._userStateModel.totalCredits,
+              MessageFactory.newWalletEntriesMsg(this._userStateModel.userStateMsg.getWalletEntries)
+            )))
 
       case false ⇒
-        self reply GetUserStateResponse(Left("No state for user %s [AQU-STA-0006]".format(event.userID)))
+        DEBUG("!haveWorkingUserState: %s", event)
+        haveAgreements match {
+          case true ⇒
+            DEBUG("haveAgreements: %s", event)
+            sender ! GetUserWalletResponse(
+              Right(
+                GetUserWalletResponseData(
+                  this.userID,
+                  Real.toMsgField(aquarium.initialUserBalance(this.unsafeUserCreationIMEventMsg.getRole, this.unsafeUserCreationIMEventMsg.getOccurredMillis)),
+                  MessageFactory.newWalletEntriesMsg()
+                )))
+
+          case false ⇒
+            DEBUG("!haveUserCreationIMEvent: %s", event)
+            sender ! GetUserWalletResponse(Left("No wallet for user %s [AQU-WAL-00 8]".format(event.userID)), 404)
+        }
     }
   }
 
+  /**
+   * Initializes the actor's internal state.
+   *
+   * @param userID
+   */
+  def onSetUserActorUserID(userID: String) {
+    // Create the full agreement history from the original sources (IMEvents)
+    this._userStateModel = ModelFactory.newInitialUserStateModel(
+      userID,
+      Real(0),
+      TimeHelpers.nowMillis()
+    )
+
+    require(this._userStateModel.isInitial, "this._userStateModel.isInitial")
+  }
+
   private[this] def D_userID = {
-    this._userID
+    if(haveUserState) userID else "???"
   }
 
   private[this] def DEBUG(fmt: String, args: Any*) =