Skip to content

Commit e87db5e

Browse files
committed
**chore(scheduler): refactor platform-specific schedulers and remove unused Bukkit/Paper classes**
- Deleted unused `BukkitSharedInstance`, `PaperSharedInstance`, `FoliaSharedScheduler`, and other legacy scheduler classes. - Replaced redundant implementations with `BukkitScheduler` and `FoliaScheduler` for unified scheduling logic. - Updated `GradewayPlugin` (Paper) to dynamically detect and use Folia or Bukkit schedulers. - Refactored event listeners to directly use `Gradeway` instances instead of `SharedInstance`. - Simplified "isFolia" detection logic with Papermc's server build utilities. - Migrated test setup for scheduling, introducing `TestScheduler` across unit tests in common modules. - Removed outdated interfaces (`SharedInstance`, `SharedScheduler`) and unused dependencies. - Fixed handling in command confirmations, renaming the task parameter to `handler` for clarity. - Introduced `BungeeCordScheduler` and `VelocityScheduler` for other platforms' alignment with new scheduling architecture. - Extended `buildSrc` for Jackson dependencies compatible with YAML processing in `plugin-yml`. - Removed obsolete dependencies such as `arrow-fx-coroutines` and `commons-configuration2`.
1 parent 1f69f20 commit e87db5e

46 files changed

Lines changed: 652 additions & 222 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎buildSrc/build.gradle.kts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,8 @@ dependencies {
1717
implementation(gradlePlugins.jetbrains.kotlin)
1818
implementation(gradlePlugins.jetbrains.kotlin.kapt)
1919
implementation(gradlePlugins.jetbrains.kotlin.plugin.serialization)
20+
21+
// Fix Jackson compatibility for plugin-yml
22+
implementation("com.fasterxml.jackson.core:jackson-databind:2.17.1")
23+
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.1")
2024
}

‎core-api/build.gradle.kts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ plugins {
66
}
77

88
dependencies {
9-
implementation(libs.google.devtools.ksp)
9+
compileOnly(libs.google.devtools.ksp)
1010
implementation(libs.kotlinx.serialization.json)
1111
implementation(libs.apache.commons.compress)
1212

‎core-api/src/main/kotlin/dev/gradienttim/gradeway/GradewayLifecycle.kt‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import dev.gradienttim.gradeway.managers.*
88
import dev.gradienttim.gradeway.platform.Caches
99
import dev.gradienttim.gradeway.platform.Environment
1010
import dev.gradienttim.gradeway.platform.Logger
11+
import dev.gradienttim.gradeway.platform.Scheduler
1112
import dev.gradienttim.gradeway.utilities.lifecycle.*
12-
import kotlinx.coroutines.CoroutineScope
1313
import java.io.File
1414
import java.time.Instant
1515

@@ -65,14 +65,13 @@ interface GradewayLifecycle<TPlatformConfig> : Gradeway<TPlatformConfig>, Loadab
6565
val logger: Logger
6666

6767
/**
68-
* A coroutine scope for fire-and-forget background side-tasks (e.g., best-effort cleanup work
69-
* that should not block whatever hot path triggered it) that are tied to the Gradeway lifecycle.
68+
* Provides task scheduling capabilities for the GradewayLifecycle system.
7069
*
71-
* The scope is recreated fresh on every [load] and canceled on every [unload], so background
72-
* work launched here is guaranteed to be torn down alongside the database and other resources
73-
* it may depend on, rather than being able to outlive them across a reload.
70+
* The `scheduler` variable allows the execution of tasks either immediately, after a specified delay,
71+
* or periodically at fixed intervals. It acts as a utility for managing asynchronous behaviors,
72+
* ensuring proper execution timing of operations within the system.
7473
*/
75-
val backgroundScope: CoroutineScope
74+
val scheduler: Scheduler
7675

7776
/**
7877
* Represents the root directory for the Gradeway system's runtime files,

‎core-api/src/main/kotlin/dev/gradienttim/gradeway/managers/ConfirmationManager.kt‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,28 @@ Copyright (c) 2026 GradientTim
55
package dev.gradienttim.gradeway.managers
66

77
import arrow.core.Either
8+
import dev.gradienttim.gradeway.platform.Scheduler
89
import dev.gradienttim.gradeway.utilities.lifecycle.Disableable
9-
import dev.gradienttim.gradeway.utilities.lifecycle.Loadable
10-
import dev.gradienttim.gradeway.utilities.lifecycle.Unloadable
1110
import net.kyori.adventure.audience.Audience
12-
import java.util.concurrent.ScheduledFuture
1311

1412
/**
1513
* Interface for managing confirmation operations, including scheduling tasks for confirmation
1614
* and handling task cancellations. Implementors of this interface are expected to manage the
1715
* lifecycle of scheduled confirmations and ensure proper cleanup when disabled.
1816
*/
19-
interface ConfirmationManager : Loadable, Unloadable, Disableable {
17+
interface ConfirmationManager : Disableable {
2018
val jobs: Set<Job>
2119

2220
/**
2321
* Schedules a task for execution and sets up a timeout handler for the task.
2422
*
2523
* @param sender The sender who requested the task.
26-
* @param task The function representing the task to be scheduled for execution.
24+
* @param handler The function representing the task to be scheduled for execution.
2725
* @param onTimeout The function to invoke when the task times out. Receives the task's unique identifier as a parameter.
2826
* @return An Either containing a [RequestJobError] if the task scheduling fails,
2927
* or a String representing the unique identifier of the scheduled task if successful.
3028
*/
31-
fun request(sender: Audience, task: () -> Unit, onTimeout: (id: String) -> Unit): Either<RequestJobError, String>
29+
fun request(sender: Audience, handler: () -> Unit, onTimeout: (id: String) -> Unit): Either<RequestJobError, String>
3230

3331
/**
3432
* Confirms a scheduled task identified by its unique identifier.
@@ -60,12 +58,12 @@ interface ConfirmationManager : Loadable, Unloadable, Disableable {
6058

6159
data class Job(
6260
val id: String,
63-
val task: () -> Unit,
64-
val scheduler: ScheduledFuture<*>,
61+
val task: Scheduler.Task,
62+
val handler: () -> Unit,
6563
val sender: Audience
6664
) {
6765
fun cancel(): Boolean {
68-
return !scheduler.isCancelled && scheduler.cancel(true)
66+
return task.cancel()
6967
}
7068

7169
override fun equals(other: Any?): Boolean {
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
MIT License
3+
Copyright (c) 2026 GradientTim
4+
*/
5+
package dev.gradienttim.gradeway.platform
6+
7+
import java.util.concurrent.TimeUnit
8+
9+
/**
10+
* Represents a scheduler interface for managing and executing tasks in a platform-independent manner.
11+
* Provides methods for running tasks immediately, with a delay, or on a repeating timer.
12+
*/
13+
interface Scheduler {
14+
/**
15+
* Executes the provided task immediately on the current thread.
16+
*
17+
* @param task A lambda function representing the task to be executed.
18+
*/
19+
fun runTask(task: () -> Unit)
20+
21+
/**
22+
* Schedules a task to be executed after a specified delay.
23+
*
24+
* @param delay The amount of time to wait before executing the task. Defaults to `1`.
25+
* @param unit The time unit of the delay parameter. Defaults to `TimeUnit.MILLISECONDS`.
26+
* @param task The lambda function representing the task to be executed.
27+
* @return An instance of [Task] that can be used to cancel the scheduled task.
28+
*/
29+
fun runTaskLater(delay: Long = 1, unit: TimeUnit = TimeUnit.MILLISECONDS, task: () -> Unit): Task
30+
31+
/**
32+
* Schedules a task to run on a repeating timer with an optional initial delay.
33+
*
34+
* @param delay The initial delay before the task is first executed. Defaults to `1`.
35+
* @param delayUnit The time unit for the delay parameter. Defaults to `TimeUnit.MILLISECONDS`.
36+
* @param interval The interval between consecutive executions of the task. Defaults to `1`.
37+
* @param intervalUnit The time unit for the period parameter. Defaults to `TimeUnit.SECONDS`.
38+
* @param task The lambda function representing the task to be executed repeatedly.
39+
* @return An instance of [Task] that can be used to cancel the scheduled task.
40+
*/
41+
fun runTaskTimer(
42+
delay: Long = 1,
43+
delayUnit: TimeUnit = TimeUnit.MILLISECONDS,
44+
interval: Long = 1,
45+
intervalUnit: TimeUnit = TimeUnit.SECONDS,
46+
task: () -> Unit
47+
): Task
48+
49+
/**
50+
* Represents a cancellable task, typically used with a scheduler to manage
51+
* execution of operations in a controlled and interruptible manner.
52+
*
53+
* Tasks can be canceled if they are no longer required to prevent unnecessary
54+
* execution or resource consumption.
55+
*/
56+
interface Task {
57+
/**
58+
* Cancels the execution of a task.
59+
* This method is intended to prevent the task from continuing or starting if it is already scheduled or running.
60+
* Once a task is canceled, its associated resources may be released, and it will no longer be executed.
61+
*
62+
* @return `true` if the task was successfully canceled, `false` if the task was already canceled or could not be canceled.
63+
*/
64+
fun cancel(): Boolean
65+
}
66+
}

‎core-common/build.gradle.kts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ dependencies {
1212
api(project(":core-api"))
1313

1414
implementation(libs.apache.commons.compress)
15-
implementation(libs.apache.commons.configuration2)
1615

1716
implementation(libs.kotlinx.serialization.json)
1817
implementation(libs.kotlinx.serialization.protobuf)

‎core-common/src/main/kotlin/dev/gradienttim/gradeway/CommonGradeway.kt‎

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import dev.gradienttim.gradeway.services.*
1313
import dev.gradienttim.gradeway.throwables.GradewayAlreadyLoadedThrowable
1414
import dev.gradienttim.gradeway.throwables.GradewayAlreadyUnloadedThrowable
1515
import dev.gradienttim.gradeway.throwables.GradewayNotLoadedThrowable
16-
import kotlinx.coroutines.*
1716
import kotlinx.serialization.KSerializer
1817
import net.kyori.adventure.text.minimessage.MiniMessage
1918
import org.jetbrains.exposed.v1.jdbc.Database
@@ -24,17 +23,16 @@ import org.koin.core.context.stopKoin
2423
import org.koin.dsl.module
2524
import java.io.File
2625
import java.time.Instant
27-
import kotlin.time.Duration.Companion.milliseconds
2826

2927
class CommonGradeway<TPlatformConfig>(
3028
override val logger: Logger,
29+
override val scheduler: Scheduler,
3130
override val directory: File,
3231
override val defaultPlatformConfig: TPlatformConfig,
3332
val platformConfigSerializer: KSerializer<TPlatformConfig>,
3433
) : GradewayLifecycle<TPlatformConfig>, KoinComponent {
3534
override val now: () -> Instant = { Instant.now() }
3635
override val caches: Caches by inject()
37-
override var backgroundScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
3836

3937
override val permissions: PermissionService by inject()
4038
override val attributes: AttributeService by inject()
@@ -59,14 +57,12 @@ class CommonGradeway<TPlatformConfig>(
5957
internal lateinit var miniMessage: MiniMessage
6058
internal lateinit var database: Database
6159

62-
private var expiredRoleSweepJob: Job? = null
60+
private var expiredRoleSweepTask: Scheduler.Task? = null
6361

6462
override fun load(): Either<Throwable, Unit> = either {
6563
if (!state.allowLoad) raise(GradewayAlreadyLoadedThrowable())
6664
state = GradewayState.PROCESSING
6765

68-
backgroundScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
69-
7066
val serviceModule = module {
7167
single<PermissionService> { CommonPermissionService(this@CommonGradeway) }
7268
single<AttributeService> { CommonAttributeService(this@CommonGradeway) }
@@ -76,7 +72,7 @@ class CommonGradeway<TPlatformConfig>(
7672
}
7773

7874
val managerModule = module {
79-
single<ConfirmationManager> { CommonConfirmationManager() }
75+
single<ConfirmationManager> { CommonConfirmationManager(this@CommonGradeway) }
8076
// createdAtStart: the migrate command looks strategies up in MigrationStrategyRegistry directly,
8177
// before ever touching gradeway.migrations, so the registrations CommonMigrationManager's init
8278
// block performs must already have happened - a lazily created single would run them too late.
@@ -108,7 +104,6 @@ class CommonGradeway<TPlatformConfig>(
108104
drivers.load().onLeft { raise(it) }
109105
languages.load().onLeft { raise(it) }
110106
messaging.load().onLeft { raise(it) }
111-
confirmations.load().onLeft { raise(it) }
112107

113108
state = GradewayState.LOADED
114109
}.onLeft {
@@ -120,9 +115,7 @@ class CommonGradeway<TPlatformConfig>(
120115
state = GradewayState.PROCESSING
121116

122117
caches.invalidateAll()
123-
backgroundScope.cancel()
124118

125-
confirmations.unload().onLeft { raise(it) }
126119
messaging.unload().onLeft { raise(it) }
127120
languages.unload().onLeft { raise(it) }
128121
drivers.unload().onLeft { raise(it) }
@@ -152,22 +145,19 @@ class CommonGradeway<TPlatformConfig>(
152145

153146
val expireRolesJobIntervalSeconds =
154147
maxOf(configs.config.sweep.expiredRoleSweepIntervalSeconds, MIN_EXPIRED_ROLE_SWEEP_INTERVAL_SECONDS)
155-
expiredRoleSweepJob = backgroundScope.launch {
156-
while (isActive) {
157-
@Suppress("MagicNumber")
158-
delay((expireRolesJobIntervalSeconds * 1000).milliseconds)
159-
players.removeExpiredRoles().onLeft {
160-
logger.warn("Failed to sweep expired player roles: $it")
161-
}
148+
149+
expiredRoleSweepTask = scheduler.runTaskTimer(interval = expireRolesJobIntervalSeconds) {
150+
players.removeExpiredRoles().onLeft {
151+
logger.warn("Failed to sweep expired player roles: $it")
162152
}
163153
}
164154
}
165155

166156
override fun disable(): Either<Throwable, Unit> = either {
167157
checkIsLoaded()
168158

169-
expiredRoleSweepJob?.cancel()
170-
expiredRoleSweepJob = null
159+
expiredRoleSweepTask?.cancel()
160+
expiredRoleSweepTask = null
171161

172162
databases.disable().onLeft { raise(it) }
173163
messaging.disable().onLeft { raise(it) }

‎core-common/src/main/kotlin/dev/gradienttim/gradeway/commands/extensions/CloudCommandHelpers.kt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ internal fun <C : Any, TListResult> MutableCommandBuilder<C>.registerEntityPermi
436436

437437
gradeway.confirmations.request(
438438
sender = audience,
439-
task = {
439+
handler = {
440440
handleClearPermissions(idOrName)
441441
.onLeft { error ->
442442
if (error is ClearPermissionsError.EntityNotFound) {
@@ -1023,7 +1023,7 @@ internal fun <C : Any, TListResult> MutableCommandBuilder<C>.registerEntityAttri
10231023

10241024
gradeway.confirmations.request(
10251025
sender = audience,
1026-
task = {
1026+
handler = {
10271027
handleClearAttributes(idOrName)
10281028
.onLeft { error ->
10291029
if (error is ClearAttributesError.EntityNotFound) {

‎core-common/src/main/kotlin/dev/gradienttim/gradeway/commands/gradeway/BackupCommand.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ internal fun <C : Any> MutableCommandBuilder<C>.registerBackupCommand(
2222
fun handleImport(audience: Audience, fileName: String, wipe: Boolean = true) {
2323
gradeway.confirmations.request(
2424
sender = audience,
25-
task = {
25+
handler = {
2626
gradeway.backups.import(fileName, wipe)
2727
.onLeft { error ->
2828
if (error is BackupManager.ImportError.FileNotFound) {

‎core-common/src/main/kotlin/dev/gradienttim/gradeway/commands/gradeway/GroupCommand.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ internal fun <C : Any> MutableCommandBuilder<C>.registerGroupCommand(
9797

9898
gradeway.confirmations.request(
9999
sender = audience,
100-
task = {
100+
handler = {
101101
gradeway.groups.delete(idOrName)
102102
.onLeft { error ->
103103
if (error is GroupService.DeleteGroupError.EntityNotFound) {

0 commit comments

Comments
 (0)