Use finagle instead of spray for the REST functionality
[aquarium] / src / main / scala / gr / grnet / aquarium / store / memory / MemStoreProvider.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.store.memory
37
38 import com.ckkloverdos.props.Props
39 import com.ckkloverdos.maybe.Just
40 import gr.grnet.aquarium.store._
41 import scala.collection.JavaConversions._
42 import collection.mutable.ConcurrentMap
43 import java.util.concurrent.ConcurrentHashMap
44 import gr.grnet.aquarium.Configurable
45 import gr.grnet.aquarium.event.model.PolicyEntry
46 import gr.grnet.aquarium.event.model.im.{StdIMEvent, IMEventModel}
47 import org.bson.types.ObjectId
48 import gr.grnet.aquarium.event.model.resource.{StdResourceEvent, ResourceEventModel}
49 import gr.grnet.aquarium.computation.state.UserState
50 import gr.grnet.aquarium.util.Tags
51 import gr.grnet.aquarium.computation.BillingMonthInfo
52
53 /**
54  * An implementation of various stores that persists parts in memory.
55  *
56  * This is just for testing purposes.
57  * 
58  * @author Christos KK Loverdos <loverdos@gmail.com>
59  * @author Georgios Gousios <gousiosg@gmail.com>
60  */
61
62 class MemStoreProvider extends UserStateStore
63   with Configurable with PolicyStore
64   with ResourceEventStore with IMEventStore
65   with StoreProvider {
66
67   override type IMEvent = MemIMEvent
68   override type ResourceEvent = MemResourceEvent
69
70   private[this] var _userStates     = List[UserState]()
71   private[this] var _policyEntries  = List[PolicyEntry]()
72   private[this] var _resourceEvents = List[ResourceEvent]()
73
74   private[this] val imEventById: ConcurrentMap[String, MemIMEvent] = new ConcurrentHashMap[String, MemIMEvent]()
75
76
77   def propertyPrefix = None
78
79   def configure(props: Props) = {
80   }
81
82   override def toString = {
83     val map = Map(
84       Tags.UserStateTag     -> _userStates.size,
85       Tags.ResourceEventTag -> _resourceEvents.size,
86       Tags.IMEventTag       -> imEventById.size,
87       "PolicyEntry"         -> _policyEntries.size
88     )
89
90     "MemStoreProvider(%s)" format map
91   }
92
93   //+ StoreProvider
94   def userStateStore = this
95
96   def resourceEventStore = this
97
98   def imEventStore = this
99
100   def policyStore = this
101   //- StoreProvider
102
103
104   //+ UserStateStore
105   def insertUserState(userState: UserState): UserState = {
106     _userStates = userState.copy(_id = new ObjectId().toString) :: _userStates
107     userState
108   }
109
110   def findUserStateByUserID(userID: String) = {
111     _userStates.find(_.userID == userID)
112   }
113
114   def findLatestUserStateForFullMonthBilling(userID: String, bmi: BillingMonthInfo): Option[UserState] = {
115     val goodOnes = _userStates.filter(_.theFullBillingMonth.isDefined).filter { userState ⇒
116         val f1 = userState.userID == userID
117         val f2 = userState.isFullBillingMonthState
118         val bm = userState.theFullBillingMonth.get
119         val f3 = bm == bmi
120
121         f1 && f2 && f3
122     }
123     
124     goodOnes.sortWith {
125       case (us1, us2) ⇒
126         us1.occurredMillis > us2.occurredMillis
127     } match {
128       case head :: _ ⇒
129         Some(head)
130       case _ ⇒
131         None
132     }
133   }
134   //- UserStateStore
135
136   //+ ResourceEventStore
137   def createResourceEventFromOther(event: ResourceEventModel): ResourceEvent = {
138     if(event.isInstanceOf[MemResourceEvent]) event.asInstanceOf[MemResourceEvent]
139     else {
140       import event._
141       new StdResourceEvent(
142         id,
143         occurredMillis,
144         receivedMillis,
145         userID,
146         clientID,
147         resource,
148         instanceID,
149         value,
150         eventVersion,
151         details
152       ): MemResourceEvent
153     }
154   }
155
156   override def clearResourceEvents() = {
157     _resourceEvents = Nil
158   }
159
160   def pingResourceEventStore(): Unit = {
161     // We are always live and kicking...
162   }
163
164   def insertResourceEvent(event: ResourceEventModel) = {
165     val localEvent = createResourceEventFromOther(event)
166     _resourceEvents ::= localEvent
167     localEvent
168   }
169
170   def findResourceEventByID(id: String) = {
171     _resourceEvents.find(ev ⇒ ev.id == id)
172   }
173
174   def findResourceEventsByUserID(userId: String)
175                                 (sortWith: Option[(ResourceEvent, ResourceEvent) => Boolean]): List[ResourceEvent] = {
176     val byUserId = _resourceEvents.filter(_.userID == userId).toArray
177     val sorted = sortWith match {
178       case Some(sorter) ⇒
179         byUserId.sortWith(sorter)
180       case None ⇒
181         byUserId
182     }
183
184     sorted.toList
185   }
186
187   def countOutOfSyncResourceEventsForBillingPeriod(userID: String, startMillis: Long, stopMillis: Long): Long = {
188     _resourceEvents.filter { case ev ⇒
189       ev.userID == userID &&
190       // out of sync events are those that were received in the billing month but occurred in previous (or next?)
191       // months
192       ev.isOutOfSyncForBillingPeriod(startMillis, stopMillis)
193     }.size.toLong
194   }
195   //- ResourceEventStore
196
197   def foreachResourceEventOccurredInPeriod(
198       userID: String,
199       startMillis: Long,
200       stopMillis: Long
201   )(f: ResourceEvent ⇒ Unit): Unit = {
202     _resourceEvents.filter { case ev ⇒
203       ev.userID == userID &&
204       ev.isOccurredWithinMillis(startMillis, stopMillis)
205     }.foreach(f)
206   }
207
208   //+ IMEventStore
209   def createIMEventFromJson(json: String) = {
210     StdIMEvent.fromJsonString(json)
211   }
212
213   def createIMEventFromOther(event: IMEventModel) = {
214     StdIMEvent.fromOther(event)
215   }
216
217   def pingIMEventStore(): Unit = {
218   }
219
220
221   def insertIMEvent(event: IMEventModel) = {
222     val localEvent = createIMEventFromOther(event)
223     imEventById += (event.id -> localEvent)
224     localEvent
225   }
226
227   def findIMEventByID(id: String) = imEventById.get(id)
228
229
230   /**
231    * Find the `CREATE` even for the given user. Note that there must be only one such event.
232    */
233   def findCreateIMEventByUserID(userID: String): Option[IMEvent] = {
234     imEventById.valuesIterator.filter { e ⇒
235       e.userID == userID && e.isCreateUser
236     }.toList.sortWith { case (e1, e2) ⇒
237       e1.occurredMillis < e2.occurredMillis
238     } headOption
239   }
240
241   def findLatestIMEventByUserID(userID: String): Option[IMEvent] = {
242     imEventById.valuesIterator.filter(_.userID == userID).toList.sortWith {
243       case (us1, us2) ⇒
244         us1.occurredMillis > us2.occurredMillis
245     } headOption
246   }
247
248   /**
249    * Scans events for the given user, sorted by `occurredMillis` in ascending order and runs them through
250    * the given function `f`.
251    *
252    * Any exception is propagated to the caller. The underlying DB resources are properly disposed in any case.
253    */
254   def foreachIMEventInOccurrenceOrder(userID: String)(f: (IMEvent) => Unit) = {
255     imEventById.valuesIterator.filter(_.userID == userID).toSeq.sortWith {
256       case (ev1, ev2) ⇒ ev1.occurredMillis <= ev2.occurredMillis
257     } foreach(f)
258   }
259   //- IMEventStore
260
261   def loadPolicyEntriesAfter(after: Long) =
262     _policyEntries.filter(p => p.validFrom > after)
263             .sortWith((a,b) => a.validFrom < b.validFrom)
264
265   def storePolicyEntry(policy: PolicyEntry) = {_policyEntries = policy :: _policyEntries; Just(RecordID(policy.id))}
266
267   def updatePolicyEntry(policy: PolicyEntry) =
268     _policyEntries = _policyEntries.foldLeft(List[PolicyEntry]()){
269       (acc, p) =>
270         if (p.id == policy.id)
271           policy :: acc
272         else
273           p :: acc
274   }
275
276   def findPolicyEntry(id: String) = {
277     _policyEntries.find(p => p.id == id)
278   }
279 }
280
281 object MemStoreProvider {
282   final def isLocalIMEvent(event: IMEventModel) = event match {
283     case _: MemIMEvent ⇒ true
284     case _ ⇒ false
285   }
286 }