Advertisement
Guest User

Untitled

a guest
Jul 24th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.94 KB | None | 0 0
  1. package su.hil.tesseract.internal
  2.  
  3. import akka.actor.ActorRef
  4. import akka.cluster.Cluster
  5. import akka.cluster.ddata.Replicator._
  6. import akka.cluster.ddata._
  7. import akka.dispatch.Futures
  8. import akka.pattern.ask
  9. import su.hil.tesseract.utils.{ Utils, Complete }
  10.  
  11. import scala.concurrent.Future
  12. import Context._
  13.  
  14. /** Creation date: 27.06.2015
  15.   * Copyright (c) harati
  16.   */
  17.  
  18. /** Асинхронная статистика тессеракта
  19.   */
  20. object Statistics extends Module {
  21.  
  22.     private val countersKey = PNCounterMapKey("stats.counters")
  23.  
  24.     private var replicator: ActorRef = _
  25.  
  26.     def push(f: ServerData)(implicit context: Context) = (replicator ? Update(countersKey, f.counters, WriteLocal)(x ⇒ x)).mapTo[UpdateSuccess[_]]
  27.  
  28.     import Context._
  29.  
  30.     def pull(implicit context: Context): Future[ServerData] = (for (
  31.         f ← ask(replicator, Get(countersKey, ReadLocal));
  32.         result = f
  33.     ) yield result).map {
  34.         case f @ GetSuccess(firstKey: PNCounterMapKey, firstData)new ServerData(f.get(firstKey))
  35.         case NotFound(key, q)throw new StatsRetrieveException
  36.     }
  37.  
  38.     private def empty(implicit context: Context): ServerData = new ServerData(PNCounterMap().increment("online", 0))
  39.  
  40.     private[internal] class ServerData(
  41.             private[internal] var counters: PNCounterMap)(implicit context: Context) {
  42.  
  43.         def online = counters.get("online").get
  44.         def onlineInc(): Unit = counters = counters.increment("online")
  45.         def onlineDec(): Unit = counters = counters.decrement("online")
  46.  
  47.         def push() = Statistics.push(this)
  48.  
  49.     }
  50.  
  51.     override def name: String = "Statistics"
  52.  
  53.     override def stop(implicit context: Context): Future[Complete] = Futures.successful(Complete())
  54.  
  55.     override def priority: Int = 0
  56.  
  57.     override def start(implicit creator: Core): Future[Complete] = {
  58.         replicator = DistributedData(creator.context.system).replicator
  59.         push(empty)
  60.         Futures.successful(Complete())
  61.     }
  62. }
  63.  
  64. class StatsRetrieveException extends RuntimeException
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement