Skip to content

Commit

Permalink
feature: Find servers by id and game type
Browse files Browse the repository at this point in the history
  • Loading branch information
utfunderscore committed Aug 25, 2024
1 parent d77c176 commit 13ea02c
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@ interface ServerService {
@GET("/server/list")
suspend fun getAllServers(): ApiResponse<List<Server>>

@GET("/server")
@GET("/server/byId")
suspend fun getServer(
@Query("serverId") serverId: UUID,
): ApiResponse<Server>

@GET("/server/byType")
suspend fun getServer(
@Query("serverType") serverType: String,
): ApiResponse<List<Server>>
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class ApiTests {
@Test
fun testGetPort() {
runBlocking {
println(orchestratorApi.getPort("b1666f1bf723"))
println(orchestratorApi.getPort("894475dac0c0"))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class ClientManager(

private val networkManager = ClientNetworkManager(packetManager, serverId)
private val executorService: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
private val serverManager = ServerManager(serverId, serverAddress, supportedGameTypes, gameFinderTypes, networkManager, executorService)
val serverManager = ServerManager(serverId, serverAddress, supportedGameTypes, gameFinderTypes, networkManager, executorService)
val gameManager = GameManager(networkManager, serverId, executorService, gameRequestHandler)

init {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import org.readutf.orchestrator.shared.game.GameFinderType
import org.readutf.orchestrator.shared.game.GameState
import org.readutf.orchestrator.shared.server.ServerAddress
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

Expand All @@ -29,26 +30,32 @@ class ShepardClient(

private val logger = KotlinLogging.logger { }

fun start() {
mainExecutor.submit { start(emptyMap()) }
fun start(): CompletableFuture<Unit> {
val future = CompletableFuture<Unit>()
mainExecutor.submit {
start(emptyMap())
future.complete(Unit)
}
return future
}

private fun start(games: Map<UUID, Game>) {
logger.info { "Connecting to server ($serverAddress)" }

reconnecting = false
ClientManager(
orchestratorHost,
orchestratorPort,
serverId,
serverAddress,
gameFinderTypes,
supportedGameTypes,
games,
gameRequestHandler,
) {
onDisconnect(it)
}
clientManager =
ClientManager(
orchestratorHost,
orchestratorPort,
serverId,
serverAddress,
gameFinderTypes,
supportedGameTypes,
games,
gameRequestHandler,
) {
onDisconnect(it)
}
}

fun setGameRequestHandler(gameRequestHandler: GameRequestHandler) {
Expand Down Expand Up @@ -82,6 +89,19 @@ class ShepardClient(
return this
}

fun setAttribute(
key: String,
any: Any,
) {
if (!isActive()) throw Exception("Not connected.")
clientManager!!.serverManager.setAttribute(key, any)
}

fun removeAttribute(key: String) {
if (!isActive()) throw Exception("Not connected.")
clientManager!!.serverManager.removeAttribute(key)
}

fun registerGame(
id: UUID,
matchType: String,
Expand All @@ -102,4 +122,10 @@ class ShepardClient(
}, 5, TimeUnit.SECONDS)
}
}

fun isActive(): Boolean {
logger.info { "Client Manager: $clientManager" }
logger.info { "Reconnecting?: $reconnecting" }
return clientManager != null && !reconnecting
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class Orchestrator(
setupPacketManager(serverManager, gameManager, kryo)

Thread({
commandManager.register(ServerCommand(serverManager, gameManager))
commandManager.register(ServerCommand(kryo, serverManager, gameManager))
commandManager.pollInput()
}, "Command Thread").start()

Expand Down
20 changes: 0 additions & 20 deletions Server/src/main/kotlin/org/readutf/orchestrator/server/Test.kt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.readutf.orchestrator.server.api

import io.javalin.Javalin
import io.javalin.community.routing.annotations.AnnotatedRouting.Annotated
import io.javalin.community.routing.annotations.HandlerResultConsumer
import org.readutf.orchestrator.server.api.endpoint.DockerEndpoint
import org.readutf.orchestrator.server.api.endpoint.GameRequestSocket
import org.readutf.orchestrator.server.api.endpoint.ServerEndpoint
Expand All @@ -10,6 +11,7 @@ import org.readutf.orchestrator.server.game.GameManager
import org.readutf.orchestrator.server.server.ServerManager
import org.readutf.orchestrator.server.settings.Settings
import org.readutf.orchestrator.server.utils.FastJsonMapper
import org.readutf.orchestrator.shared.utils.ApiResponse

class EndpointManager(
val settings: Settings,
Expand Down Expand Up @@ -47,6 +49,11 @@ class EndpointManager(
config.router.mount(Annotated) { routing ->
routing.registerEndpoints(ServerEndpoint(serverManager))
routing.registerEndpoints(DockerEndpoint(DockerManager(settings.dockerSettings)))

routing.registerResultHandler(
ApiResponse::class.java,
HandlerResultConsumer { ctx, value -> ctx.json(value) },
)
}

config.pvt.internalRouter.allHttpHandlers().forEach { parsedEndpoint ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import io.javalin.community.routing.annotations.Get
import io.javalin.community.routing.annotations.Query
import io.javalin.http.Context
import org.readutf.orchestrator.server.server.ServerManager
import org.readutf.orchestrator.shared.server.Server
import org.readutf.orchestrator.shared.utils.ApiResponse
import java.util.UUID

Expand All @@ -13,27 +14,30 @@ class ServerEndpoint(
val serverManager: ServerManager,
) {
@Get("list")
fun listServers(context: Context) {
context.json(ApiResponse.success(serverManager.getAllServers()))
}
fun listServers(context: Context): ApiResponse<List<Server>> = ApiResponse.success(serverManager.getAllServers() as List<Server>)

@Get("")
@Get("byId")
fun getServer(
context: Context,
@Query("serverId") serverIdString: String,
) {
): ApiResponse<Server> {
val serverId =
try {
UUID.fromString(serverIdString)
} catch (e: Exception) {
context.json(ApiResponse.failure<String>("Invalid uuid 'serverId'"))
return
return ApiResponse.failure("Invalid uuid 'serverId'")
}

serverManager.getServerById(serverId)?.let {
context.json(ApiResponse.success(it))
} ?: run {
context.json(ApiResponse.failure<String>("Could not find server with that id"))
return serverManager.getServerById(serverId)?.let { server ->
ApiResponse.success(server)
} ?: let { _ ->
ApiResponse.failure("Could not find server with that id")
}
}

@Get("byType")
fun getServerByType(
context: Context,
@Query("serverType") gameType: String,
): ApiResponse<List<Server>> = ApiResponse.success(serverManager.getServersByType(gameType))
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package org.readutf.orchestrator.server.server

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONWriter
import com.esotericsoftware.kryo.kryo5.Kryo
import com.esotericsoftware.kryo.kryo5.Registration
import org.readutf.orchestrator.server.game.GameManager
import org.readutf.orchestrator.shared.server.Server
import revxrsal.commands.annotation.Command
Expand All @@ -11,6 +13,7 @@ import revxrsal.commands.ktx.returnWithMessage

@Command("server")
class ServerCommand(
private val kryo: Kryo,
private val serverManager: ServerManager,
private val gameManager: GameManager,
) {
Expand Down Expand Up @@ -49,6 +52,20 @@ class ServerCommand(
}
}

@Subcommand("debug")
fun debug() {
var previous: Registration? = null
var i = 0
while ((i == 0 || previous != null) && i++ < 5000) {
previous = kryo.getRegistration(i)
if (previous != null) {
println("$i: ${previous.type}")
} else {
break
}
}
}

fun getServerInfoLines(server: Server): List<String> =
listOf(
"${server.getShortId()} ${JSON.toJSONString(server, JSONWriter.Feature.PrettyFormat)}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import io.github.oshai.kotlinlogging.KotlinLogging
import org.readutf.orchestrator.server.server.store.ServerStore
import org.readutf.orchestrator.shared.server.Server
import org.readutf.orchestrator.shared.server.ServerHeartbeat
import org.readutf.orchestrator.shared.utils.TypedObject
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit.*

class ServerManager(
private val serverStore: ServerStore,
Expand All @@ -20,7 +22,7 @@ class ServerManager(
{ invalidateExpiredServers() },
0,
5,
java.util.concurrent.TimeUnit.SECONDS,
SECONDS,
)
}

Expand Down Expand Up @@ -60,9 +62,9 @@ class ServerManager(
fun setAttribute(
serverId: UUID,
attributeName: String,
any: Any,
typedObject: TypedObject,
) {
serverStore.setAttribute(serverId, attributeName, any)
serverStore.setAttribute(serverId, attributeName, typedObject)
}

fun removeAttribute(
Expand All @@ -75,4 +77,6 @@ class ServerManager(
fun getServerByShortId(shortId: String): Server? = serverStore.getServerByShortId(shortId)

fun getServerById(serverId: UUID): Server? = serverStore.getServerById(serverId)

fun getServersByType(serverType: String): List<Server> = serverStore.getServersByType(serverType)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.readutf.orchestrator.server.server.store
import org.readutf.orchestrator.server.server.RegisteredServer
import org.readutf.orchestrator.shared.server.Server
import org.readutf.orchestrator.shared.server.ServerHeartbeat
import org.readutf.orchestrator.shared.utils.TypedObject
import java.util.UUID

interface ServerStore {
Expand All @@ -28,11 +29,13 @@ interface ServerStore {
fun setAttribute(
serverId: UUID,
attributeName: String,
any: Any,
typedObject: TypedObject,
)

fun removeAttribute(
serverId: UUID,
attributeName: String,
)

fun getServersByType(gameType: String): List<Server>
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ class MemoryServerStore : ServerStore {
override fun setAttribute(
serverId: UUID,
attributeName: String,
data: TypedObject,
typedObject: TypedObject,
) {
val serverById = getServerById(serverId) ?: return

serverById.attributes[attributeName] = data
serverById.attributes[attributeName] = typedObject
}

override fun removeAttribute(
Expand All @@ -62,6 +62,8 @@ class MemoryServerStore : ServerStore {
serverById.attributes.remove(attributeName)
}

override fun getServersByType(gameType: String): List<Server> = servers.values.filter { server -> server.gameTypes.contains(gameType) }

override fun getTimedOutServers(): List<RegisteredServer> {
val now = System.currentTimeMillis()
return servers.values.filter { it.heartbeat.timestamp < now - 15000 }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,8 @@ class H2ServerStore : ServerStore {
) {
TODO("Not yet implemented")
}

override fun getServersByType(gameType: String): List<Server> {
TODO("Not yet implemented")
}
}

0 comments on commit 13ea02c

Please sign in to comment.