865aa02223fae5d77774f848c596c49016148c97
[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 import gr.grnet.aquarium.actor._
41 import gr.grnet.aquarium.user._
42
43 import gr.grnet.aquarium.util.shortClassNameOf
44 import gr.grnet.aquarium.util.chainOfCauses
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 gr.grnet.aquarium.{AquariumException, Configurator}
51
52
53 /**
54  *
55  * @author Christos KK Loverdos <loverdos@gmail.com>
56  */
57
58 class UserActor extends ReflectiveRoleableActor {
59   private[this] var _userID: String = _
60   private[this] var _userState: UserState = _
61
62   self.lifeCycle = Temporary
63
64   private[this] def _shutmedown(): Unit = {
65     if(_haveFullState) {
66       UserActorCache.invalidate(this._userID)
67     }
68
69     self.stop()
70   }
71
72   override protected def onThrowable(t: Throwable, message: AnyRef) = {
73     ERROR("Oops!\n", chainOfCauses(t).map("!! " + _) mkString "\n")
74     ERROR(t, "Terminating due to: %s(%s)", shortClassNameOf(t), t.getMessage)
75
76     _shutmedown()
77   }
78
79   def role = UserActorRole
80
81   private[this] def _configurator: Configurator = Configurator.MasterConfigurator
82 //  private[this] def _userId = _userState.userId
83
84   private[this] def _timestampTheshold =
85     _configurator.props.getLong(Configurator.Keys.user_state_timestamp_threshold).getOr(10000)
86
87
88   private[this] def _haveFullState = {
89     (this._userID ne null) && (this._userState ne null)
90   }
91
92   def onAquariumPropertiesLoaded(event: AquariumPropertiesLoaded): Unit = {
93   }
94
95   def onActorProviderConfigured(event: ActorProviderConfigured): Unit = {
96   }
97
98   private[this] def _computeAgreementForNewUser(imEvent: IMEventModel): String = {
99     // FIXME: Implement based on the role
100     "default"
101   }
102
103   private[this] def processCreateUser(imEvent: IMEventModel): Unit = {
104     val userID = imEvent.userID
105     this._userID = userID
106
107     val store = _configurator.storeProvider.userStateStore
108     // try find user state. normally should ot exist
109     val latestUserStateOpt = store.findLatestUserStateByUserID(userID)
110     if(latestUserStateOpt.isDefined) {
111       logger.error("Got %s(%s, %s) but user already exists. Ingoring".format(
112         userID,
113         shortClassNameOf(imEvent),
114         imEvent.eventType))
115
116       return
117     }
118
119     val initialAgreementName = _computeAgreementForNewUser(imEvent)
120     val newUserState    = DefaultUserStateComputations.createInitialUserState(
121       userID,
122       imEvent.occurredMillis,
123       imEvent.isActive,
124       0.0,
125       List(imEvent.role),
126       initialAgreementName)
127
128     this._userState = newUserState
129
130     // FIXME: If this fails, then the actor must be shut down.
131     store.insertUserState(newUserState)
132   }
133
134   private[this] def processModifyUser(imEvent: IMEventModel): Unit = {
135     val now = TimeHelpers.nowMillis()
136
137     if(!_haveFullState) {
138       ERROR("Got %s(%s) but have no state. Shutting down", shortClassNameOf(imEvent), imEvent.eventType)
139       _shutmedown()
140       return
141     }
142
143     this._userState = this._userState.modifyFromIMEvent(imEvent, now)
144   }
145
146   def onProcessSetUserID(event: ProcessSetUserID): Unit = {
147     this._userID = event.userID
148   }
149
150   def onProcessIMEvent(event: ProcessIMEvent): Unit = {
151     val imEvent = event.imEvent
152     if(imEvent.isCreateUser) {
153       processCreateUser(imEvent)
154     } else if(imEvent.isModifyUser) {
155       processModifyUser(imEvent)
156     } else {
157       throw new AquariumException("Cannot interpret %s".format(imEvent))
158     }
159   }
160
161   def onRequestUserBalance(event: RequestUserBalance): Unit = {
162     val userId = event.userID
163     // FIXME: Implement threshold
164     self reply UserResponseGetBalance(userId, _userState.creditsSnapshot.creditAmount)
165   }
166
167   def onUserRequestGetState(event: UserRequestGetState): Unit = {
168     val userId = event.userID
169    // FIXME: implement
170     self reply UserResponseGetState(userId, this._userState)
171   }
172
173   def onProcessResourceEvent(event: ProcessResourceEvent): Unit = {
174   }
175
176
177   private[this] def D_userID = {
178     if(this._userID eq null)
179       "<NOT INITIALIZED>" // We always get a userID first
180     else
181       if(this._userState eq null)
182         "%s, NO STATE".format(this._userID)
183       else
184         "%s".format(this._userID)
185   }
186
187   private[this] def DEBUG(fmt: String, args: Any*) =
188     logger.debug("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
189
190   private[this] def INFO(fmt: String, args: Any*) =
191     logger.info("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
192
193   private[this] def WARN(fmt: String, args: Any*) =
194     logger.warn("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
195
196   private[this] def ERROR(fmt: String, args: Any*) =
197     logger.error("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)))
198
199   private[this] def ERROR(t: Throwable, fmt: String, args: Any*) =
200       logger.error("UserActor[%s]: %s".format(D_userID, fmt.format(args: _*)), t)
201 }