Skip to content

Instantly share code, notes, and snippets.

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>gameoflife</artifactId>
<groupId>com.wakaleo.gameoflife</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.wakaleo.gameoflife</groupId>
<artifactId>gameoflife-web</artifactId>
case class PostMessageRequest(userID: UserID, message: String) extends ConversationRestEntities
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val postMessageRequestFormat = jsonFormat2(PostMessageRequest)
}
class ConversationRoutes(sessionHandler: ActorRef[SessionHandlerCommand])(implicit
val system: ActorSystem[_]
) extends JsonSupport { ... }
lazy val conversationRoutes: Route = {
concat(
pathPrefix(version / "conversation" / LongNumber) { conversationID =>
post {
entity(as[PostMessageRequest]) {
pmr =>
val maybeSessionGranted: Future[SessionEvent] =
getSession(conversationID, pmr.userID)
onComplete(maybeSessionGranted) {
def getSession(conversationID: ConversationID, userID: UserID): Future[SessionEvent] =
sessionHandler.ask(GetSession(conversationID, userID, _))
onComplete(maybeSessionGranted) {
case Success(SessionGranted(session)) =>
postMessage(conversationID, pmr.userID, pmr.message)(session)
complete(OK, PostMessageResponse(pmr.message))
case Failure(_) =>
complete(BadRequestError, "Authentication Failed")
case _ => complete(InternalServerError)
}
def postMessage(conversationID: ConversationID, sender: UserID, message: String)(
session: ActorRef[SessionCommand]
): Unit =
session ! PostMessage(conversationID, sender, message)
private def idle(): ConversationBehavior = {
timers.startSingleTimer(TimerKey, ConversationTimeout, sessionTimeout)
this
}
case ConversationTimeout =>
sessionHandler ! SessionTimeout(conversationID)
// This will also stop the event sourced actor
Behaviors.stopped
case SessionTimeout(conversationID) =>
sessions -= conversationID // remove session from the cache
context.log.info(s"Session timed out for conversation ${conversationID}")
this