This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
forked from mamoe/mirai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.kt
647 lines (564 loc) · 24.6 KB
/
select.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
* Copyright 2020 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/master/LICENSE
*/
@file:Suppress("DuplicatedCode")
package net.mamoe.mirai.event
import kotlinx.coroutines.*
import net.mamoe.mirai.message.MessageEvent
import net.mamoe.mirai.message.data.Message
import net.mamoe.mirai.message.data.PlainText
import net.mamoe.mirai.message.isContextIdenticalWith
import net.mamoe.mirai.message.nextMessage
import net.mamoe.mirai.utils.MiraiExperimentalAPI
import kotlin.jvm.JvmName
import kotlin.jvm.JvmSynthetic
/**
* 挂起当前协程, 等待任意一个事件监听器返回 `false` 后返回.
*
* 创建的所有事件监听器都会判断发送人信息 ([isContextIdenticalWith]), 监听之后的所有消息.
*
* [selectBuilder] DSL 类似于 [CoroutineScope.subscribeMessages] 的 DSL, 屏蔽了一些 `reply` DSL 以确保类型安全
*
* ```kotlin
* reply("开启复读模式")
*
* whileSelectMessages {
* "stop" {
* reply("已关闭复读")
* false // 停止循环
* }
* // 也可以使用 startsWith("") { true } 等 DSL
* default {
* reply(message)
* true // 继续循环
* }
* timeout(3000) {
* // on
* true
* }
* } // 等待直到 `false`
*
* reply("复读模式结束")
* ```
*
* @param timeoutMillis 超时. 单位为毫秒. `-1` 为不限制
*
* @see subscribe
* @see subscribeMessages
* @see nextMessage 挂起协程并等待下一条消息
*/
@Suppress("unused")
suspend inline fun <reified T : MessageEvent> T.whileSelectMessages(
timeoutMillis: Long = -1,
filterContext: Boolean = true,
priority: Listener.EventPriority = EventPriority.MONITOR,
crossinline selectBuilder: @MessageDsl MessageSelectBuilder<T, Boolean>.() -> Unit
) = whileSelectMessagesImpl(timeoutMillis, filterContext, priority, selectBuilder)
/**
* [selectMessages] 的 [Unit] 返回值捷径 (由于 Kotlin 无法推断 [Unit] 类型)
*/
@MiraiExperimentalAPI
@JvmName("selectMessages1")
suspend inline fun <reified T : MessageEvent> T.selectMessagesUnit(
timeoutMillis: Long = -1,
filterContext: Boolean = true,
priority: Listener.EventPriority = EventPriority.MONITOR,
crossinline selectBuilder: @MessageDsl MessageSelectBuilderUnit<T, Unit>.() -> Unit
) = selectMessagesImpl(timeoutMillis, true, filterContext, priority, selectBuilder)
/**
* 挂起当前协程, 等待任意一个事件监听器触发后返回其返回值.
*
* 创建的所有事件监听器都会判断发送人信息 ([isContextIdenticalWith]), 监听之后的所有消息.
*
* [selectBuilder] DSL 类似于 [CoroutineScope.subscribeMessages] 的 DSL, 屏蔽了一些 `reply` DSL 以确保类型安全
*
* ```kotlin
* val value: String = selectMessages {
* "hello" { "111" }
* "hi" { "222" }
* startsWith("/") { it }
* default { "default" }
* }
* ```
*
* @param timeoutMillis 超时. 单位为毫秒. `-1` 为不限制
*
* @see nextMessage 挂起协程并等待下一条消息
*/
@Suppress("unused") // false positive
// @BuilderInference // https://youtrack.jetbrains.com/issue/KT-37716
suspend inline fun <reified T : MessageEvent, R> T.selectMessages(
timeoutMillis: Long = -1,
filterContext: Boolean = true,
priority: Listener.EventPriority = EventPriority.MONITOR,
// @BuilderInference
crossinline selectBuilder: @MessageDsl MessageSelectBuilder<T, R>.() -> Unit
): R =
selectMessagesImpl(timeoutMillis,
false,
filterContext,
priority) { selectBuilder.invoke(this as MessageSelectBuilder<T, R>) }
/**
* [selectMessages] 时的 DSL 构建器.
*
* 它是特殊化的消息监听 ([CoroutineScope.subscribeMessages]) DSL, 屏蔽了一些 `reply` DSL 以确保作用域安全性
*
* @see MessageSelectBuilderUnit 查看上层 API
*/
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
abstract class MessageSelectBuilder<M : MessageEvent, R> @PublishedApi internal constructor(
ownerMessagePacket: M,
stub: Any?,
subscriber: (M.(String) -> Boolean, MessageListener<M, Any?>) -> Unit
) : MessageSelectBuilderUnit<M, R>(ownerMessagePacket, stub, subscriber) {
// 这些函数无法获取返回值. 必须屏蔽.
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun <N : Any> mapping(
mapper: M.(String) -> N?,
onEvent: @MessageDsl suspend M.(N) -> R
) = error("prohibited")
@Deprecated("Use `default` instead", level = DeprecationLevel.HIDDEN)
override fun always(onEvent: MessageListener<M, Any?>) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.reply(block: suspend () -> Any?): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.reply(message: String): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.reply(message: Message): Nothing = error("prohibited")
@JvmName("reply3")
@Suppress(
"INAPPLICABLE_JVM_NAME", "unused", "UNCHECKED_CAST",
"INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName"
)
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.`->`(message: String): Nothing = error("prohibited")
@JvmName("reply3")
@Suppress(
"INAPPLICABLE_JVM_NAME", "unused", "UNCHECKED_CAST",
"INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName"
)
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.`->`(message: Message): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.quoteReply(block: suspend () -> Any?): Nothing =
error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.quoteReply(message: String): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override infix fun MessageSelectionTimeoutChecker.quoteReply(message: Message): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.containsReply(reply: String): Nothing = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.containsReply(replier: suspend M.(String) -> Any?) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun Regex.matchingReply(replier: suspend M.(MatchResult) -> Any?) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun Regex.findingReply(replier: suspend M.(MatchResult) -> Any?) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.endsWithReply(replier: suspend M.(String) -> Any?) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.reply(reply: String) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.reply(reply: Message) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun String.reply(replier: suspend M.(String) -> Any?) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.reply(toReply: String) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.reply(message: Message) = error("prohibited")
@JvmName("reply3")
@Suppress("INAPPLICABLE_JVM_NAME", "INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.`->`(toReply: String) = error("prohibited")
@JvmName("reply3")
@Suppress("INAPPLICABLE_JVM_NAME", "INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.`->`(message: Message) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.reply(replier: suspend M.(String) -> Any?) =
error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.quoteReply(toReply: String) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.quoteReply(toReply: Message) = error("prohibited")
@Deprecated("Using `reply` DSL in message selection is prohibited", level = DeprecationLevel.HIDDEN)
override fun ListeningFilter.quoteReply(replier: suspend M.(String) -> Any?) = error("prohibited")
}
/**
* [selectMessagesUnit] 或 [selectMessages] 时的 DSL 构建器.
*
* 它是特殊化的消息监听 ([CoroutineScope.subscribeMessages]) DSL
*
* @see MessageSubscribersBuilder 查看上层 API
*/
abstract class MessageSelectBuilderUnit<M : MessageEvent, R> @PublishedApi internal constructor(
private val ownerMessagePacket: M,
stub: Any?,
subscriber: (M.(String) -> Boolean, MessageListener<M, Any?>) -> Unit
) : MessageSubscribersBuilder<M, Unit, R, Any?>(stub, subscriber) {
/**
* 当其他条件都不满足时的默认处理.
*/
@MessageDsl
abstract fun default(onEvent: MessageListener<M, R>) // 需要后置默认监听器
@Deprecated("Use `default` instead", level = DeprecationLevel.HIDDEN)
override fun always(onEvent: MessageListener<M, Any?>) = error("prohibited")
/**
* 限制本次 select 的最长等待时间, 当超时后抛出 [TimeoutCancellationException]
*/
@Suppress("NOTHING_TO_INLINE")
@MessageDsl
fun timeoutException(
timeoutMillis: Long,
exception: () -> Throwable = { throw MessageSelectionTimeoutException() }
) {
require(timeoutMillis > 0) { "timeoutMillis must be positive" }
obtainCurrentCoroutineScope().launch {
delay(timeoutMillis)
val deferred = obtainCurrentDeferred() ?: return@launch
if (deferred.isActive && !deferred.isCompleted) {
deferred.completeExceptionally(exception())
}
}
}
/**
* 限制本次 select 的最长等待时间, 当超时后执行 [block] 以完成 select
*/
@MessageDsl
fun timeout(timeoutMillis: Long, block: suspend () -> R) {
require(timeoutMillis > 0) { "timeoutMillis must be positive" }
obtainCurrentCoroutineScope().launch {
delay(timeoutMillis)
val deferred = obtainCurrentDeferred() ?: return@launch
if (deferred.isActive && !deferred.isCompleted) {
deferred.complete(block())
}
}
}
/**
* 返回一个限制本次 select 的最长等待时间的 [Deferred]
*
* @see invoke
* @see reply
*/
@MessageDsl
fun timeout(timeoutMillis: Long): MessageSelectionTimeoutChecker {
require(timeoutMillis > 0) { "timeoutMillis must be positive" }
return MessageSelectionTimeoutChecker(timeoutMillis)
}
/**
* 返回一个限制本次 select 的最长等待时间的 [Deferred]
*
* @see Deferred<Unit>.invoke
*/
@Suppress("unused")
fun MessageSelectionTimeoutChecker.invoke(block: suspend () -> R) {
return timeout(this.timeoutMillis, block)
}
/**
* 在超时后回复原消息
*
* 当 [block] 返回值为 [Unit] 时不回复, 为 [Message] 时回复 [Message], 其他将 [toString] 后回复为 [PlainText]
*
* @see timeout
* @see quoteReply
*/
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.reply(block: suspend () -> Any?) {
return timeout(this.timeoutMillis) {
executeAndReply(block)
Unit as R
}
}
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.reply(message: Message) {
return timeout(this.timeoutMillis) {
ownerMessagePacket.reply(message)
Unit as R
}
}
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.reply(message: String) {
return timeout(this.timeoutMillis) {
ownerMessagePacket.reply(message)
Unit as R
}
}
@JvmName("reply3")
@Suppress(
"INAPPLICABLE_JVM_NAME", "unused", "UNCHECKED_CAST",
"INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName"
)
open infix fun MessageSelectionTimeoutChecker.`->`(message: Message) {
return this.reply(message)
}
@JvmName("reply3")
@Suppress(
"INAPPLICABLE_JVM_NAME", "unused", "UNCHECKED_CAST",
"INVALID_CHARACTERS", "NAME_CONTAINS_ILLEGAL_CHARS", "FunctionName"
)
open infix fun MessageSelectionTimeoutChecker.`->`(message: String) {
return this.reply(message)
}
/**
* 在超时后引用回复原消息
*
* 当 [block] 返回值为 [Unit] 时不回复, 为 [Message] 时回复 [Message], 其他将 [toString] 后回复为 [PlainText]
*
* @see timeout
* @see reply
*/
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.quoteReply(block: suspend () -> Any?) {
return timeout(this.timeoutMillis) {
executeAndQuoteReply(block)
Unit as R
}
}
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.quoteReply(message: Message) {
return timeout(this.timeoutMillis) {
ownerMessagePacket.quoteReply(message)
Unit as R
}
}
@Suppress("unused", "UNCHECKED_CAST")
open infix fun MessageSelectionTimeoutChecker.quoteReply(message: String) {
return timeout(this.timeoutMillis) {
ownerMessagePacket.quoteReply(message)
Unit as R
}
}
/**
* 当其他条件都不满足时回复原消息.
*
* 当 [block] 返回值为 [Unit] 时不回复, 为 [Message] 时回复 [Message], 其他将 [toString] 后回复为 [PlainText]
*/
@MessageDsl
fun defaultReply(block: suspend () -> Any?): Unit = subscriber({ true }, {
[email protected](block)
})
/**
* 当其他条件都不满足时引用回复原消息.
*
* 当 [block] 返回值为 [Unit] 时不回复, 为 [Message] 时回复 [Message], 其他将 [toString] 后回复为 [PlainText]
*/
@MessageDsl
fun defaultQuoteReply(block: suspend () -> Any?): Unit = subscriber({ true }, {
[email protected](block)
})
private suspend inline fun executeAndReply(noinline block: suspend () -> Any?) {
when (val result = block()) {
Unit -> {
}
is Message -> ownerMessagePacket.reply(result)
else -> ownerMessagePacket.reply(result.toString())
}
}
private suspend inline fun executeAndQuoteReply(noinline block: suspend () -> Any?) {
when (val result = block()) {
Unit -> {
}
is Message -> ownerMessagePacket.quoteReply(result)
else -> ownerMessagePacket.quoteReply(result.toString())
}
}
protected abstract fun obtainCurrentCoroutineScope(): CoroutineScope
protected abstract fun obtainCurrentDeferred(): CompletableDeferred<R>?
}
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
inline class MessageSelectionTimeoutChecker internal constructor(val timeoutMillis: Long)
class MessageSelectionTimeoutException : RuntimeException()
/////////////////////////
//// implementations ////
/////////////////////////
@JvmSynthetic
@PublishedApi
internal suspend inline fun <R> withSilentTimeoutOrCoroutineScope(
timeoutMillis: Long,
noinline block: suspend CoroutineScope.() -> R
): R {
require(timeoutMillis == -1L || timeoutMillis > 0) { "timeoutMillis must be -1 or > 0 " }
return withContext(ExceptionHandlerIgnoringCancellationException) {
if (timeoutMillis == -1L) {
coroutineScope(block)
} else {
withTimeout(timeoutMillis, block)
}
}
}
@PublishedApi
internal val SELECT_MESSAGE_STUB = Any()
@PublishedApi
internal val ExceptionHandlerIgnoringCancellationException = CoroutineExceptionHandler { _, throwable ->
if (throwable !is CancellationException) {
throw throwable
}
}
@PublishedApi
@BuilderInference
internal suspend inline fun <reified T : MessageEvent, R> T.selectMessagesImpl(
timeoutMillis: Long = -1,
isUnit: Boolean,
filterContext: Boolean = true,
priority: Listener.EventPriority,
@BuilderInference
crossinline selectBuilder: @MessageDsl MessageSelectBuilderUnit<T, R>.() -> Unit
): R = withSilentTimeoutOrCoroutineScope(timeoutMillis) {
var deferred: CompletableDeferred<R>? = CompletableDeferred()
coroutineContext[Job]!!.invokeOnCompletion {
deferred?.cancel()
}
// ensure sequential invoking
val listeners: MutableList<Pair<T.(String) -> Boolean, MessageListener<T, Any?>>> = mutableListOf()
val defaultListeners: MutableList<MessageListener<T, Any?>> = mutableListOf()
if (isUnit) {
// https://youtrack.jetbrains.com/issue/KT-37716
val outside = { filter: T.(String) -> Boolean, listener: MessageListener<T, Any?> ->
listeners += filter to listener
}
object : MessageSelectBuilderUnit<T, R>(
this@selectMessagesImpl,
SELECT_MESSAGE_STUB,
outside
) {
override fun obtainCurrentCoroutineScope(): CoroutineScope = this@withSilentTimeoutOrCoroutineScope
override fun obtainCurrentDeferred(): CompletableDeferred<R>? = deferred
override fun default(onEvent: MessageListener<T, R>) {
defaultListeners += onEvent
}
}
} else {
// https://youtrack.jetbrains.com/issue/KT-37716
val outside = { filter: T.(String) -> Boolean, listener: MessageListener<T, Any?> ->
listeners += filter to listener
}
object : MessageSelectBuilder<T, R>(
this@selectMessagesImpl,
SELECT_MESSAGE_STUB,
outside
) {
override fun obtainCurrentCoroutineScope(): CoroutineScope = this@withSilentTimeoutOrCoroutineScope
override fun obtainCurrentDeferred(): CompletableDeferred<R>? = deferred
override fun default(onEvent: MessageListener<T, R>) {
defaultListeners += onEvent
}
}
}.apply(selectBuilder)
// we don't have any way to reduce duplication yet,
// until local functions are supported in inline functions
@Suppress("DuplicatedCode") val subscribeAlways = subscribeAlways<T>(
concurrency = Listener.ConcurrencyKind.LOCKED,
priority = priority
) { event ->
if (filterContext && !this.isContextIdenticalWith(this@selectMessagesImpl))
return@subscribeAlways
val toString = event.message.contentToString()
listeners.forEach { (filter, listener) ->
if (deferred?.isCompleted == true || !isActive)
return@subscribeAlways
if (filter.invoke(event, toString)) {
// same to the one below
val value = listener.invoke(event, toString)
if (value !== SELECT_MESSAGE_STUB) {
@Suppress("UNCHECKED_CAST")
deferred?.complete(value as R)
return@subscribeAlways
} else if (isUnit) { // value === stub
// unit mode: we can directly complete this selection
@Suppress("UNCHECKED_CAST")
deferred?.complete(Unit as R)
}
}
}
defaultListeners.forEach { listener ->
// same to the one above
val value = listener.invoke(event, toString)
if (value !== SELECT_MESSAGE_STUB) {
@Suppress("UNCHECKED_CAST")
deferred?.complete(value as R)
return@subscribeAlways
} else if (isUnit) { // value === stub
// unit mode: we can directly complete this selection
@Suppress("UNCHECKED_CAST")
deferred?.complete(Unit as R)
}
}
}
deferred!!.await().also {
subscribeAlways.complete()
deferred = null
coroutineContext.cancelChildren()
}
}
@Suppress("unused")
@PublishedApi
internal suspend inline fun <reified T : MessageEvent> T.whileSelectMessagesImpl(
timeoutMillis: Long,
filterContext: Boolean,
priority: Listener.EventPriority,
crossinline selectBuilder: @MessageDsl MessageSelectBuilder<T, Boolean>.() -> Unit
) = withSilentTimeoutOrCoroutineScope(timeoutMillis) {
var deferred: CompletableDeferred<Boolean>? = CompletableDeferred()
coroutineContext[Job]!!.invokeOnCompletion {
deferred?.cancel()
}
// ensure sequential invoking
val listeners: MutableList<Pair<T.(String) -> Boolean, MessageListener<T, Any?>>> = mutableListOf()
val defaultListeners: MutableList<MessageListener<T, Any?>> = mutableListOf()
// https://youtrack.jetbrains.com/issue/KT-37716
val outside = { filter: T.(String) -> Boolean, listener: MessageListener<T, Any?> ->
listeners += filter to listener
}
object : MessageSelectBuilder<T, Boolean>(
this@whileSelectMessagesImpl,
SELECT_MESSAGE_STUB,
outside
) {
override fun obtainCurrentCoroutineScope(): CoroutineScope = this@withSilentTimeoutOrCoroutineScope
override fun obtainCurrentDeferred(): CompletableDeferred<Boolean>? = deferred
override fun default(onEvent: MessageListener<T, Boolean>) {
defaultListeners += onEvent
}
}.apply(selectBuilder)
// ensure atomic completing
val subscribeAlways = subscribeAlways<T>(
concurrency = Listener.ConcurrencyKind.LOCKED,
priority = priority
) { event ->
if (filterContext && !this.isContextIdenticalWith(this@whileSelectMessagesImpl))
return@subscribeAlways
val toString = event.message.contentToString()
listeners.forEach { (filter, listener) ->
if (deferred?.isCompleted != false || !isActive)
return@subscribeAlways
if (filter.invoke(event, toString)) {
listener.invoke(event, toString).let { value ->
if (value !== SELECT_MESSAGE_STUB) {
deferred?.complete(value as Boolean)
return@subscribeAlways // accept the first value only
}
}
}
}
defaultListeners.forEach { listener ->
listener.invoke(event, toString).let { value ->
if (value !== SELECT_MESSAGE_STUB) {
deferred?.complete(value as Boolean)
return@subscribeAlways // accept the first value only
}
}
}
}
while (deferred?.await() == true) {
deferred = CompletableDeferred()
}
subscribeAlways.complete()
deferred = null
coroutineContext.cancelChildren()
}