Skip to content

Commit

Permalink
Avoid scheduling new coroutines when not necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
chatasma committed Jul 13, 2024
1 parent e702774 commit da8aa6b
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 36 deletions.
12 changes: 12 additions & 0 deletions src/main/kotlin/network/warzone/mars/Mars.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import org.bukkit.plugin.java.JavaPlugin
import tc.oc.pgm.api.PGM
import tc.oc.pgm.tablist.MatchTabManager
import java.util.*
import java.util.concurrent.CompletableFuture

class Mars : JavaPlugin() {
companion object {
Expand All @@ -44,6 +45,17 @@ class Mars : JavaPlugin() {
}
}

fun asyncAsFuture(block: suspend() -> Unit) : CompletableFuture<Void?> {
val future = CompletableFuture<Void?>()
Bukkit.getScheduler().runTaskAsynchronously(get()) {
runBlocking {
block.invoke()
future.complete(null)
}
}
return future
}

fun sync(block: () -> Unit) = Bukkit.getScheduler().runTask(get(), block) // Run next tick

fun get() = instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ object BroadcastFeature : Feature<Broadcast>() {
return broadcasts.find { it.name.equals(target, ignoreCase = true) }
}

override fun fetchCached(target: String): Broadcast? {
return broadcasts.find { it.name.equals(target, ignoreCase = true) }
}

override suspend fun init() {
index = 0
broadcasts = BroadcastService.getBroadcasts()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import app.ashcon.intake.argument.ArgumentParseException
import app.ashcon.intake.argument.CommandArgs
import app.ashcon.intake.argument.Namespace
import app.ashcon.intake.bukkit.parametric.provider.BukkitProvider
import kotlinx.coroutines.runBlocking
import network.warzone.mars.broadcast.Broadcast
import network.warzone.mars.broadcast.BroadcastFeature
import network.warzone.mars.broadcast.exceptions.BroadcastMissingException
Expand All @@ -15,13 +14,13 @@ class BroadcastProvider : BukkitProvider<Broadcast> {
return "broadcast"
}

override fun get(sender: CommandSender?, args: CommandArgs, annotations: MutableList<out Annotation>?): Broadcast = runBlocking {
override fun get(sender: CommandSender?, args: CommandArgs, annotations: MutableList<out Annotation>?): Broadcast {
val broadcastName = args.next()

val broadcast: Broadcast? = BroadcastFeature.fetch(broadcastName)
val broadcast: Broadcast? = BroadcastFeature.fetchCached(broadcastName)
broadcast ?: throw ArgumentParseException(BroadcastMissingException(broadcastName).asTextComponent().content())

return@runBlocking broadcast
return broadcast
}

override fun getSuggestions(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import app.ashcon.intake.argument.ArgumentParseException
import app.ashcon.intake.argument.CommandArgs
import app.ashcon.intake.argument.Namespace
import app.ashcon.intake.bukkit.parametric.provider.BukkitProvider
import kotlinx.coroutines.runBlocking
import network.warzone.mars.player.feature.PlayerFeature
import network.warzone.mars.player.feature.exceptions.PlayerNotOnlineException
import network.warzone.mars.player.models.PlayerProfile
Expand All @@ -20,13 +19,13 @@ class PlayerProfileProvider : BukkitProvider<PlayerProfile> {
sender: CommandSender?,
args: CommandArgs,
annotations: MutableList<out Annotation>?
): PlayerProfile = runBlocking {
): PlayerProfile {
val name = args.next()

val profile = PlayerFeature.getCached(name) // Only online players
profile ?: throw ArgumentParseException(PlayerNotOnlineException(name).asTextComponent().content())

return@runBlocking profile
return profile
}

override fun getSuggestions(
Expand Down
5 changes: 5 additions & 0 deletions src/main/kotlin/network/warzone/mars/feature/Feature.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ abstract class Feature<T : Resource> {
*/
abstract suspend fun fetch(target: String): T?

/**
* Query cache exclusively
*/
open fun fetchCached(target: String): T? { return null }

/**
* Get resource from cache first, and API if not in cache.
* Defaults to API fetch if feature has no cache.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package network.warzone.mars.match.tracker

import kotlinx.coroutines.runBlocking
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.Component.text
import net.kyori.adventure.text.format.NamedTextColor
Expand Down Expand Up @@ -100,12 +99,12 @@ class PlayerTracker : Listener {

// todo: set XP bar progress & level (and ensure compatibility with vanilla exp)
@EventHandler
fun onPlayerXPGain(event: PlayerXPGainEvent) = runBlocking {
fun onPlayerXPGain(event: PlayerXPGainEvent) {
val (id, gain, reason, notify, multiplier) = event.data

val context = PlayerManager.getPlayer(id) ?: return@runBlocking
val context = PlayerManager.getPlayer(id) ?: return
val player = context.player
val profile = context.getPlayerProfile()
val profile = context.getPlayerProfileCached() ?: return

val currentLevel = profile.stats.level

Expand All @@ -126,7 +125,7 @@ class PlayerTracker : Listener {
}

@EventHandler
fun onPlayerLevelUp(event: PlayerLevelUpEvent) = runBlocking {
fun onPlayerLevelUp(event: PlayerLevelUpEvent) {
val (player, level) = event.data

player.playSound(player.location, Sound.LEVEL_UP, 1000f, 1f)
Expand Down
4 changes: 4 additions & 0 deletions src/main/kotlin/network/warzone/mars/player/PlayerContext.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,8 @@ class PlayerContext(val uuid: UUID, val player: Player, val activeSession: Sessi
// The player is online so we know they exist.
return PlayerFeature.getKnown(uuid)
}

fun getPlayerProfileCached(): PlayerProfile? {
return PlayerFeature.getCached(uuid)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class AchievementMenu(player: Player) : Listener {
}

// Navigate the player up the menu hierarchy.
private fun createBackArrow(action: suspend InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
private fun createBackArrow(action: InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
return {
item = item(Material.ARROW) {
name = "${ChatColor.GRAY}Back"
Expand All @@ -164,7 +164,7 @@ class AchievementMenu(player: Player) : Listener {
}

// Navigate the player to the next page of a paginated GUI.
private fun createNextPageArrow(currentPage: Int, action: suspend InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
private fun createNextPageArrow(currentPage: Int, action: InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
return {
item = item(Material.ARROW) {
name = "${ChatColor.GRAY}Next Page"
Expand All @@ -175,7 +175,7 @@ class AchievementMenu(player: Player) : Listener {
}

// Navigate the player to the previous page of a paginated GUI.
private fun createPreviousPageArrow(currentPage: Int, action: suspend InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
private fun createPreviousPageArrow(currentPage: Int, action: InventoryClickEvent.(Player) -> Unit): GUI.Slot.() -> Unit {
return {
item = item(Material.ARROW) {
name = "${ChatColor.GRAY}Previous Page"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ object PlayerFeature : NamedCachedFeature<PlayerProfile>(), Listener {
}

@EventHandler
fun onPlayerLogin(event: PlayerLoginEvent) = runBlocking {
fun onPlayerLogin(event: PlayerLoginEvent) {
val player = event.player

val (_, profile, activePuns, activeSession) = queuedJoins[player.uniqueId]
Expand Down Expand Up @@ -222,7 +222,7 @@ object PlayerFeature : NamedCachedFeature<PlayerProfile>(), Listener {
}

@EventHandler
fun onPlayerLogout(event: PlayerQuitEvent) = runBlocking {
fun onPlayerLogout(event: PlayerQuitEvent) {
Mars.async {
val player = event.player
val uuid = player.uniqueId
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package network.warzone.mars.player.level

import kotlinx.coroutines.runBlocking
import network.warzone.mars.Mars
import network.warzone.mars.match.tracker.PlayerXPGainEvent
import network.warzone.mars.player.PlayerManager
Expand Down Expand Up @@ -67,9 +66,9 @@ class LevelDisplayListener : Listener {
}

// Mars stat system level
private fun showStatsLevel(player: Player) = runBlocking {
private fun showStatsLevel(player: Player) {
val context = PlayerManager.getPlayer(player.uniqueId)
val profile = context?.getPlayerProfile()
val profile = context?.getPlayerProfileCached()
val stats = profile?.stats
player.level = stats?.level ?: 1
player.exp = (stats?.xp?.rem(5000F))?.div(5000F) ?: 0F
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package network.warzone.mars.report

import kotlinx.coroutines.runBlocking
import network.warzone.mars.Mars
import network.warzone.mars.api.socket.models.SimplePlayer
import network.warzone.mars.feature.Feature
Expand Down
20 changes: 13 additions & 7 deletions src/main/kotlin/network/warzone/mars/tag/commands/TagsCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,20 @@ class TagsCommand {
// todo: send request on GUI close so player can't spam API reqs by clicking
onclick = {
if (isActive) {
PlayerFeature.setActiveTag(context.uuid.toString(), null)
profile.activeTagId = null
Mars.asyncAsFuture {
PlayerFeature.setActiveTag(context.uuid.toString(), null)
}.thenRun {
profile.activeTagId = null
}
} else if (profile.tagIds.contains(tag._id)) {
PlayerFeature.setActiveTag(
context.uuid.toString(),
tag
)
profile.activeTagId = tag._id
Mars.asyncAsFuture {
PlayerFeature.setActiveTag(
context.uuid.toString(),
tag
)
}.thenRun {
profile.activeTagId = tag._id
}
}

refresh()
Expand Down
15 changes: 7 additions & 8 deletions src/main/kotlin/network/warzone/mars/utils/menu/GUI.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package network.warzone.mars.utils.menu

import kotlinx.coroutines.runBlocking
import network.warzone.mars.Mars
import org.bukkit.Bukkit
import org.bukkit.Sound
Expand Down Expand Up @@ -49,13 +48,13 @@ class GUI(
}

@EventHandler(priority = EventPriority.LOWEST)
fun onClick(e: InventoryClickEvent) = runBlocking {
if (e.inventory != inventory) return@runBlocking
fun onClick(e: InventoryClickEvent) {
if (e.inventory != inventory) return
e.isCancelled = true

if (e.clickedInventory != inventory) return@runBlocking
val player = e.whoClicked as? Player ?: return@runBlocking
val slot = slots.getOrNull(e.slot) ?: return@runBlocking
if (e.clickedInventory != inventory) return
val player = e.whoClicked as? Player ?: return
val slot = slots.getOrNull(e.slot) ?: return

// Play a sound if the slot has a click handler
if (slot.onclick != null) {
Expand All @@ -73,8 +72,8 @@ class GUI(

inner class Slot {
var item: Item? = null
var onclick: (suspend InventoryClickEvent.(Player) -> Unit)? = null
var sound: (suspend InventoryClickEvent.(Player) -> Unit)? = { it.playSound(it.location, Sound.ORB_PICKUP, .05f, 1f) }
var onclick: (InventoryClickEvent.(Player) -> Unit)? = null
var sound: (InventoryClickEvent.(Player) -> Unit)? = { it.playSound(it.location, Sound.ORB_PICKUP, .05f, 1f) }
}

fun slot(
Expand Down

0 comments on commit da8aa6b

Please sign in to comment.