Skip to content

Commit fe82165

Browse files
committed
Task control flow improvements
1 parent a12bcaa commit fe82165

File tree

3 files changed

+80
-57
lines changed

3 files changed

+80
-57
lines changed

common/src/main/kotlin/com/lambda/module/modules/client/TaskFlow.kt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ object TaskFlow : Module(
1414
defaultTags = setOf(ModuleTag.CLIENT, ModuleTag.AUTOMATION)
1515
) {
1616
enum class Page {
17-
BUILD, ROTATION, INTERACTION
17+
TASKS, BUILD, ROTATION, INTERACTION
1818
}
1919

2020
private val page by setting("Page", Page.BUILD)
21+
val taskCooldown by setting("Task Cooldown", 0, 0..200, 1, " ticks")
2122
val build = BuildSettings(this) {
2223
page == Page.BUILD
2324
}

common/src/main/kotlin/com/lambda/task/Task.kt

Lines changed: 72 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import com.lambda.event.EventFlow
77
import com.lambda.event.Subscriber
88
import com.lambda.event.events.TickEvent
99
import com.lambda.event.listener.SafeListener.Companion.listener
10+
import com.lambda.module.modules.client.TaskFlow
1011
import com.lambda.threading.runSafe
1112
import com.lambda.util.BaritoneUtils
1213
import com.lambda.util.Communication.logError
1314
import com.lambda.util.Communication.warn
15+
import com.lambda.util.DynamicReflectionSerializer.dynamicString
1416
import com.lambda.util.Nameable
1517
import com.lambda.util.text.buildText
1618
import com.lambda.util.text.color
@@ -51,6 +53,7 @@ abstract class Task<Result>(
5153
private var timeout: Int = Int.MAX_VALUE,
5254
private var tries: Int = 0,
5355
private var repeats: Int = 0,
56+
private var cooldown: Int = TaskFlow.taskCooldown,
5457
private var onStart: SafeContext.(Task<Result>) -> Unit = {},
5558
private var onSuccess: SafeContext.(Task<Result>, Result) -> Unit = { _, _ -> },
5659
private var onRetry: SafeContext.(Task<Result>) -> Unit = {},
@@ -68,7 +71,7 @@ abstract class Task<Result>(
6871
private var attempted = 0
6972
private val subTasks = mutableListOf<Task<*>>()
7073
private var state = State.IDLE
71-
var age: Int = 0
74+
var age = 0
7275

7376
private val isDeactivated get() = state == State.DEACTIVATED
7477
val isActivated get() = state == State.ACTIVATED
@@ -81,35 +84,6 @@ abstract class Task<Result>(
8184

8285
// ToDo: Better color management
8386
private val primaryColor = Color(0, 255, 0, 100)
84-
val info: Text
85-
get() = buildText {
86-
literal("Name ")
87-
color(primaryColor) { literal(name) }
88-
89-
literal(" State ")
90-
color(primaryColor) { literal(state.name) }
91-
92-
literal(" Runtime ")
93-
color(primaryColor) {
94-
literal(DurationFormatUtils.formatDuration(age * 50L, "HH:mm:ss,SSS").dropLast(1))
95-
}
96-
97-
val display = subTasks.reversed().take(MAX_DEBUG_ENTRIES)
98-
display.forEach {
99-
literal("\n${" ".repeat(depth + 1)}")
100-
text(it.info)
101-
}
102-
103-
val left = subTasks.size - display.size
104-
if (left > 0) {
105-
literal("\n${" ".repeat(depth + 1)}And ")
106-
color(primaryColor) {
107-
literal("$left")
108-
}
109-
literal(" more...")
110-
}
111-
112-
}
11387

11488
val syncListeners = Subscriber()
11589
private val concurrentListeners = Subscriber()
@@ -120,7 +94,7 @@ abstract class Task<Result>(
12094
DEACTIVATED,
12195
CANCELLED,
12296
FAILED,
123-
COMPLETED
97+
COMPLETED,
12498
}
12599

126100
operator fun plus(other: Task<*>) = subTasks.add(other)
@@ -184,6 +158,8 @@ abstract class Task<Result>(
184158

185159
@Ta5kBuilder
186160
fun SafeContext.success(result: Result) {
161+
LOG.info("$identifier completed successfully after $attempted retries and $executions executions.")
162+
187163
if (executions < repeats) {
188164
executions++
189165
LOG.info("Repeating $identifier $executions/$repeats...")
@@ -192,7 +168,6 @@ abstract class Task<Result>(
192168
return
193169
}
194170

195-
LOG.info("$identifier completed successfully after $attempted retries and $executions executions.")
196171
state = State.COMPLETED
197172
stopListening()
198173
onSuccess(this@Task, result)
@@ -201,6 +176,8 @@ abstract class Task<Result>(
201176

202177
@Ta5kBuilder
203178
fun cancel() {
179+
if (state == State.CANCELLED) return
180+
204181
cancelSubTasks()
205182
state = State.CANCELLED
206183
stopListening()
@@ -210,9 +187,7 @@ abstract class Task<Result>(
210187

211188
@Ta5kBuilder
212189
fun cancelSubTasks() {
213-
subTasks
214-
.filter { it.isRunning }
215-
.forEach { it.cancel() }
190+
subTasks.forEach { it.cancel() }
216191
}
217192

218193
@Ta5kBuilder
@@ -232,7 +207,6 @@ abstract class Task<Result>(
232207
onRetry(this@Task)
233208
}
234209
reset()
235-
// activate()
236210
return
237211
}
238212

@@ -265,16 +239,16 @@ abstract class Task<Result>(
265239

266240
private fun notifyParent() {
267241
parent?.let { par ->
268-
// if (par.isCompleted) {
269-
// LOG.info("$identifier notified parent ${par.identifier}")
270-
// par.notifyParent()
271-
// return@let
272-
// }
273-
274-
if (par.isActivated) return@let
275-
276-
LOG.info("$identifier reactivated parent ${par.identifier}")
277-
par.activate()
242+
when {
243+
par.isCompleted -> {
244+
LOG.info("$identifier completed parent ${par.identifier}")
245+
par.notifyParent()
246+
}
247+
!par.isActivated -> {
248+
LOG.info("$identifier reactivated parent ${par.identifier}")
249+
par.activate()
250+
}
251+
}
278252
}
279253
}
280254

@@ -362,6 +336,15 @@ abstract class Task<Result>(
362336
@Ta5kBuilder
363337
fun onSuccess(action: SafeContext.(Task<Result>, Result) -> Unit): Task<Result> {
364338
this.onSuccess = action
339+
LOG.info("Success action $action set for $identifier")
340+
return this
341+
}
342+
343+
@Ta5kBuilder
344+
fun thenRun(action: SafeContext.(Task<Result>, Result) -> Task<*>): Task<Result> {
345+
this.onSuccess = { task, result ->
346+
action(this, task, result).start(task)
347+
}
365348
return this
366349
}
367350

@@ -431,10 +414,6 @@ abstract class Task<Result>(
431414

432415
class TimeoutException(age: Int, attempts: Int) : Exception("Task timed out after $age ticks and $attempts attempts")
433416

434-
class SubTaskBuilder {
435-
val tasks = mutableListOf<Task<*>>()
436-
}
437-
438417
companion object {
439418
val MAX_DEPTH = 20
440419
const val MAX_DEBUG_ENTRIES = 15
@@ -452,7 +431,19 @@ abstract class Task<Result>(
452431
message: String
453432
): Task<Unit> = object : Task<Unit>() {
454433
init { this.name = "FailTask" }
455-
override fun SafeContext.onStart() { failure(message) }
434+
override fun SafeContext.onStart() {
435+
failure(message)
436+
}
437+
}
438+
439+
@Ta5kBuilder
440+
fun failTask(
441+
e: Throwable
442+
): Task<Unit> = object : Task<Unit>() {
443+
init { this.name = "FailTask" }
444+
override fun SafeContext.onStart() {
445+
failure(e)
446+
}
456447
}
457448

458449
@Ta5kBuilder
@@ -483,4 +474,34 @@ abstract class Task<Result>(
483474
}
484475
}
485476
}
477+
478+
val info: Text
479+
get() = buildText {
480+
literal("Name ")
481+
color(primaryColor) { literal(name) }
482+
483+
literal(" State ")
484+
color(primaryColor) { literal(state.name) }
485+
486+
literal(" Runtime ")
487+
color(primaryColor) {
488+
literal(DurationFormatUtils.formatDuration(age * 50L, "HH:mm:ss,SSS").dropLast(1))
489+
}
490+
491+
val display = subTasks.reversed().take(MAX_DEBUG_ENTRIES)
492+
display.forEach {
493+
literal("\n${" ".repeat(depth + 1)}")
494+
text(it.info)
495+
}
496+
497+
val left = subTasks.size - display.size
498+
if (left > 0) {
499+
literal("\n${" ".repeat(depth + 1)}And ")
500+
color(primaryColor) {
501+
literal("$left")
502+
}
503+
literal(" more...")
504+
}
505+
506+
}
486507
}

common/src/main/kotlin/com/lambda/task/tasks/PlaceContainer.kt

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ class PlaceContainer @Ta5kBuilder constructor(
1919
) : Task<BlockPos>() {
2020
override fun SafeContext.onStart() {
2121
val results = BlockPos.iterateOutwards(player.blockPos, 4, 3, 4)
22-
// .filter { world.isAir(it) }
2322
.map { it.blockPos }
24-
// .filter { world.isAir(it) }
2523
.flatMap {
2624
it.blockPos
2725
.toStructure(TargetState.Stack(stack))
@@ -32,10 +30,13 @@ class PlaceContainer @Ta5kBuilder constructor(
3230
// val res = results.sorted()
3331
// res
3432

35-
val useful = results.filterIsInstance<PlaceResult.Success>() + results.filterIsInstance<BuildResult.WrongStack>()
36-
useful.minOrNull()?.let { result ->
33+
val succeeds = results.filterIsInstance<PlaceResult.Success>()
34+
val wrongStacks = results.filterIsInstance<BuildResult.WrongStack>()
35+
(succeeds + wrongStacks).minOrNull()?.let { result ->
3736
buildStructure {
38-
result.blockPos.toStructure(TargetState.Stack(stack)).toBlueprint()
37+
result.blockPos
38+
.toStructure(TargetState.Stack(stack))
39+
.toBlueprint()
3940
}.onSuccess { _, _ ->
4041
success(result.blockPos)
4142
}.start(this@PlaceContainer)

0 commit comments

Comments
 (0)