Skip to content

Commit

Permalink
extract host selection
Browse files Browse the repository at this point in the history
  • Loading branch information
pschichtel committed Oct 6, 2024
1 parent 149b832 commit 7a3ba37
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
20 changes: 9 additions & 11 deletions app/controllers/Ld56C2Controller.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import java.net.InetAddress
import java.time.{Duration, Instant}
import java.util.UUID
import java.util.concurrent.{ConcurrentHashMap, ConcurrentMap}
import scala.collection.mutable.ArrayBuffer
import scala.math.Ordering.Implicits.infixOrderingOps

private val logger = Logger(classOf[Ld56C2Controller])
Expand Down Expand Up @@ -144,27 +145,20 @@ class JoinHandler(out: ActorRef,
Json.parse(text).as[JoinerMessage] match
case JoinMessage() =>
val it = hosts.entrySet().iterator()
var latestUpdate = Instant.MIN
var latestHost: GameHost = null
val viableHosts = ArrayBuffer[GameHost]()
while (it.hasNext) {
val entry = it.next()
val host = entry.getValue
if (host.lastUpdated < Instant.now().minus(Duration.ofSeconds(1000))) {
val actor = hosters.remove(entry.getKey)

it.remove()
actor ! PoisonPill
} else {
if (host.lastUpdated > latestUpdate) {
latestUpdate = host.lastUpdated
latestHost = host
}
viableHosts.append(host)
}
}
if (latestHost != null) {
hosters.get(latestHost.id) ! Json.toJson(JoiningMessage(myId)).toString
} else {
logger.warn("No host available!")
if (viableHosts.nonEmpty) {
hosters.get(pickBestHost(viableHosts.toIndexedSeq).id) ! Json.toJson(JoiningMessage(myId)).toString
}
case OfferMessage(dest, offer) =>
hosters.get(dest) ! Json.toJson(OfferingMessage(myId, offer)).toString
Expand All @@ -174,4 +168,8 @@ class JoinHandler(out: ActorRef,
case e: Exception =>
logger.error("Kaputt", e)
}

private def pickBestHost(hosts: IndexedSeq[GameHost]): GameHost = {
hosts.maxBy(_.lastUpdated)
}
}
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ libraryDependencies ++= Seq(
"com.google.apis" % "google-api-services-youtube" % "v3-rev20230822-2.0.0",
"gov.sandia.foundry" % "porter-stemmer" % "1.4",
"com.vladsch.flexmark" % "flexmark-all" % "0.64.8",
"org.webjars" % "font-awesome" % "5.15.4"
"org.webjars" % "font-awesome" % "5.15.4",
)

scalacOptions ++= Seq("-unchecked", "-deprecation")
Expand Down

0 comments on commit 7a3ba37

Please sign in to comment.