Reflective actor handles exceptions in an extensible way
[aquarium] / src / main / scala / gr / grnet / aquarium / actor / service / user / UserActor.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.aquarium.actor
37 package service
38 package user
39
40
41 import gr.grnet.aquarium.actor._
42 import gr.grnet.aquarium.user._
43
44 import gr.grnet.aquarium.util.shortClassNameOf
45 import gr.grnet.aquarium.util.date.TimeHelpers
46 import gr.grnet.aquarium.actor.message.service.router._
47 import message.config.{ActorProviderConfigured, AquariumPropertiesLoaded}
48 import gr.grnet.aquarium.event.im.IMEventModel
49 import akka.config.Supervision.Temporary
50 import akka.actor.PoisonPill
51 import gr.grnet.aquarium.{AquariumException, Configurator}
52
53
54 /**
55  *
56  * @author Christos KK Loverdos <loverdos@gmail.com>
57  */
58
59 class UserActor extends ReflectiveAquariumActor {
60   private[this] var _userID: String = _
61   private[this] var _userState: UserState = _
62
63   self.lifeCycle = Temporary
64
65   override protected def onThrowable(t: Throwable) = {
66     logger.error("Terminating due to: %s".format(t.getMessage), t)
67     UserActorCache.invalidate(this._userID)
68
69     self ! PoisonPill
70   }
71
72   def role = UserActorRole
73
74   private[this] def _configurator: Configurator = Configurator.MasterConfigurator
75 //  private[this] def _userId = _userState.userId
76
77   private[this] def _timestampTheshold =
78     _configurator.props.getLong(Configurator.Keys.user_state_timestamp_threshold).getOr(10000)
79
80
81   def onAquariumPropertiesLoaded(event: AquariumPropertiesLoaded): Unit = {
82   }
83
84   def onActorProviderConfigured(event: ActorProviderConfigured): Unit = {
85   }
86
87   private[this] def _computeAgreementForNewUser(imEvent: IMEventModel): String = {
88     // FIXME: Implement based on the role
89     "default"
90   }
91
92   private[this] def processCreateUser(imEvent: IMEventModel): Unit = {
93     val userID = imEvent.userID
94     this._userID = userID
95
96     val store = _configurator.storeProvider.userStateStore
97     // try find user state. normally should ot exist
98     val latestUserStateOpt = store.findLatestUserStateByUserID(userID)
99     if(latestUserStateOpt.isDefined) {
100       logger.error("Got %s(%s, %s) but user already exists. Ingoring".format(
101         userID,
102         shortClassNameOf(imEvent),
103         imEvent.eventType))
104
105       return
106     }
107
108     val initialAgreementName = _computeAgreementForNewUser(imEvent)
109     val newUserState    = DefaultUserStateComputations.createInitialUserState(
110       userID,
111       imEvent.occurredMillis,
112       imEvent.isActive,
113       0.0,
114       List(imEvent.role),
115       initialAgreementName)
116
117     this._userState = newUserState
118
119     // FIXME: If this fails, then the actor must be shut down.
120     store.insertUserState(newUserState)
121   }
122
123   private[this] def processModifyUser(event: IMEventModel): Unit = {
124     val now = TimeHelpers.nowMillis()
125     val newActive = ActiveStateSnapshot(event.isStateActive, now)
126
127     DEBUG("New active status = %s".format(newActive))
128
129     this._userState = this._userState.copy(activeStateSnapshot = newActive)
130   }
131
132   def onProcessIMEvent(event: ProcessIMEvent): Unit = {
133     val imEvent = event.imEvent
134     if(imEvent.isCreateUser) {
135       processCreateUser(imEvent)
136     } else if(imEvent.isModifyUser) {
137       processModifyUser(imEvent)
138     } else {
139       throw new AquariumException("Cannot interpret %s".format(imEvent))
140     }
141   }
142
143   def onRequestUserBalance(event: RequestUserBalance): Unit = {
144     val userId = event.userID
145     // FIXME: Implement threshold
146     self reply UserResponseGetBalance(userId, _userState.creditsSnapshot.creditAmount)
147   }
148
149   def onUserRequestGetState(event: UserRequestGetState): Unit = {
150     val userId = event.userID
151    // FIXME: implement
152     self reply UserResponseGetState(userId, this._userState)
153   }
154
155   def onProcessResourceEvent(event: ProcessResourceEvent): Unit = {
156   }
157
158
159   private[this] def D_userID = {
160     this._userState match {
161       case null ⇒
162         "???"
163
164       case userState ⇒
165         userState.userID
166     }
167   }
168   private[this] def DEBUG(fmt: String, args: Any*) =
169     logger.debug("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
170
171   private[this] def INFO(fmt: String, args: Any*) =
172     logger.info("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
173
174   private[this] def WARN(fmt: String, args: Any*) =
175     logger.warn("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
176
177   private[this] def ERROR(fmt: String, args: Any*) =
178     logger.error("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
179
180   private[this] def ERROR(t: Throwable, fmt: String, args: Any*) =
181       logger.error("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)), t)
182 }