Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental |
| 18 | |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 19 | import kotlinx.coroutines.experimental.internalAnnotations.* |
Roman Elizarov | 2adf8bc | 2018-01-24 20:09:57 +0300 | [diff] [blame] | 20 | import kotlinx.coroutines.experimental.intrinsics.* |
Roman Elizarov | dd90bf1 | 2018-06-08 16:32:41 +0300 | [diff] [blame] | 21 | import kotlinx.coroutines.experimental.selects.* |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 22 | import kotlinx.coroutines.experimental.timeunit.* |
Roman Elizarov | 2adf8bc | 2018-01-24 20:09:57 +0300 | [diff] [blame] | 23 | import kotlin.coroutines.experimental.* |
| 24 | import kotlin.coroutines.experimental.intrinsics.* |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 25 | |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 26 | /** |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 27 | * Runs a given suspending [block] of code inside a coroutine with a specified timeout and throws |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 28 | * [TimeoutCancellationException] if timeout was exceeded. |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 29 | * |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 30 | * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 31 | * cancellable suspending function inside the block throws [TimeoutCancellationException]. |
| 32 | * Even if the code in the block suppresses [TimeoutCancellationException], it |
| 33 | * is still thrown by `withTimeout` invocation. |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 34 | * |
| 35 | * The sibling function that does not throw exception on timeout is [withTimeoutOrNull]. |
| 36 | * Note, that timeout action can be specified for [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. |
Roman Elizarov | 9d61b3e | 2017-04-19 18:32:11 +0300 | [diff] [blame] | 37 | * |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 38 | * This function delegates to [Delay.invokeOnTimeout] if the context [CoroutineDispatcher] |
| 39 | * implements [Delay] interface, otherwise it tracks time using a built-in single-threaded scheduled executor service. |
Roman Elizarov | 9d61b3e | 2017-04-19 18:32:11 +0300 | [diff] [blame] | 40 | * |
Roman Elizarov | 19f4845 | 2017-12-21 18:48:20 +0300 | [diff] [blame] | 41 | * @param time timeout time in milliseconds. |
| 42 | */ |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 43 | public suspend fun <T> withTimeout(time: Int, block: suspend CoroutineScope.() -> T): T = |
Roman Elizarov | 19f4845 | 2017-12-21 18:48:20 +0300 | [diff] [blame] | 44 | withTimeout(time.toLong(), TimeUnit.MILLISECONDS, block) |
| 45 | |
| 46 | /** |
| 47 | * Runs a given suspending [block] of code inside a coroutine with a specified timeout and throws |
| 48 | * [TimeoutCancellationException] if timeout was exceeded. |
| 49 | * |
| 50 | * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of |
| 51 | * cancellable suspending function inside the block throws [TimeoutCancellationException]. |
| 52 | * Even if the code in the block suppresses [TimeoutCancellationException], it |
| 53 | * is still thrown by `withTimeout` invocation. |
| 54 | * |
| 55 | * The sibling function that does not throw exception on timeout is [withTimeoutOrNull]. |
| 56 | * Note, that timeout action can be specified for [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. |
| 57 | * |
| 58 | * This function delegates to [Delay.invokeOnTimeout] if the context [CoroutineDispatcher] |
| 59 | * implements [Delay] interface, otherwise it tracks time using a built-in single-threaded scheduled executor service. |
| 60 | * |
Roman Elizarov | 9d61b3e | 2017-04-19 18:32:11 +0300 | [diff] [blame] | 61 | * @param time timeout time |
| 62 | * @param unit timeout unit (milliseconds by default) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 63 | */ |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 64 | public suspend fun <T> withTimeout(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS, block: suspend CoroutineScope.() -> T): T { |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 65 | if (time <= 0L) throw CancellationException("Timed out immediately") |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 66 | return suspendCoroutineOrReturn { cont: Continuation<T> -> |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 67 | setupTimeout(TimeoutCoroutine(time, unit, cont), block) |
Roman Elizarov | 3754f95 | 2017-01-18 20:47:54 +0300 | [diff] [blame] | 68 | } |
| 69 | } |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 70 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 71 | private fun <U, T: U> setupTimeout( |
| 72 | coroutine: TimeoutCoroutine<U, T>, |
| 73 | block: suspend CoroutineScope.() -> T |
| 74 | ): Any? { |
| 75 | // schedule cancellation of this coroutine on time |
| 76 | val cont = coroutine.cont |
| 77 | val context = cont.context |
| 78 | coroutine.disposeOnCompletion(context.delay.invokeOnTimeout(coroutine.time, coroutine.unit, coroutine)) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 79 | // restart block using new coroutine with new job, |
| 80 | // however start it as undispatched coroutine, because we are already in the proper context |
Roman Elizarov | 2adf8bc | 2018-01-24 20:09:57 +0300 | [diff] [blame] | 81 | return coroutine.startUndispatchedOrReturn(coroutine, block) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 82 | } |
| 83 | |
| 84 | /** |
| 85 | * @suppress **Deprecated**: for binary compatibility only |
| 86 | */ |
| 87 | @Deprecated("for binary compatibility only", level=DeprecationLevel.HIDDEN) |
| 88 | public suspend fun <T> withTimeout(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS, block: suspend () -> T): T = |
| 89 | withTimeout(time, unit) { block() } |
| 90 | |
| 91 | private open class TimeoutCoroutine<U, in T: U>( |
| 92 | @JvmField val time: Long, |
| 93 | @JvmField val unit: TimeUnit, |
| 94 | @JvmField val cont: Continuation<U> |
| 95 | ) : AbstractCoroutine<T>(cont.context, active = true), Runnable, Continuation<T> { |
| 96 | override val defaultResumeMode: Int get() = MODE_DIRECT |
| 97 | |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 98 | @Suppress("LeakingThis") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 99 | override fun run() { |
| 100 | cancel(TimeoutCancellationException(time, unit, this)) |
| 101 | } |
| 102 | |
| 103 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | ebc8866 | 2018-01-24 23:58:56 +0300 | [diff] [blame] | 104 | internal override fun onCompletionInternal(state: Any?, mode: Int) { |
Roman Elizarov | 6640b2b | 2018-01-17 19:08:55 +0300 | [diff] [blame] | 105 | if (state is CompletedExceptionally) |
Vsevolod Tolstopyatov | c1092d5 | 2018-04-12 20:22:25 +0300 | [diff] [blame] | 106 | cont.resumeWithExceptionMode(state.cause, mode) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 107 | else |
| 108 | cont.resumeMode(state as T, mode) |
| 109 | } |
| 110 | |
| 111 | override fun nameString(): String = |
| 112 | "${super.nameString()}($time $unit)" |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 113 | } |
| 114 | |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 115 | /** |
| 116 | * Runs a given suspending block of code inside a coroutine with a specified timeout and returns |
Roman Elizarov | 607f893 | 2017-06-09 11:36:21 +0300 | [diff] [blame] | 117 | * `null` if this timeout was exceeded. |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 118 | * |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 119 | * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 120 | * cancellable suspending function inside the block throws [TimeoutCancellationException]. |
| 121 | * Even if the code in the block suppresses [TimeoutCancellationException], this |
| 122 | * invocation of `withTimeoutOrNull` still returns `null`. |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 123 | * |
| 124 | * The sibling function that throws exception on timeout is [withTimeout]. |
| 125 | * Note, that timeout action can be specified for [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. |
| 126 | * |
| 127 | * This function delegates to [Delay.invokeOnTimeout] if the context [CoroutineDispatcher] |
| 128 | * implements [Delay] interface, otherwise it tracks time using a built-in single-threaded scheduled executor service. |
| 129 | * |
Roman Elizarov | 19f4845 | 2017-12-21 18:48:20 +0300 | [diff] [blame] | 130 | * @param time timeout time in milliseconds. |
| 131 | */ |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 132 | public suspend fun <T> withTimeoutOrNull(time: Int, block: suspend CoroutineScope.() -> T): T? = |
Roman Elizarov | 19f4845 | 2017-12-21 18:48:20 +0300 | [diff] [blame] | 133 | withTimeoutOrNull(time.toLong(), TimeUnit.MILLISECONDS, block) |
| 134 | |
| 135 | /** |
| 136 | * Runs a given suspending block of code inside a coroutine with a specified timeout and returns |
| 137 | * `null` if this timeout was exceeded. |
| 138 | * |
| 139 | * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of |
| 140 | * cancellable suspending function inside the block throws [TimeoutCancellationException]. |
| 141 | * Even if the code in the block suppresses [TimeoutCancellationException], this |
| 142 | * invocation of `withTimeoutOrNull` still returns `null`. |
| 143 | * |
| 144 | * The sibling function that throws exception on timeout is [withTimeout]. |
| 145 | * Note, that timeout action can be specified for [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. |
| 146 | * |
| 147 | * This function delegates to [Delay.invokeOnTimeout] if the context [CoroutineDispatcher] |
| 148 | * implements [Delay] interface, otherwise it tracks time using a built-in single-threaded scheduled executor service. |
| 149 | * |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 150 | * @param time timeout time |
| 151 | * @param unit timeout unit (milliseconds by default) |
| 152 | */ |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 153 | public suspend fun <T> withTimeoutOrNull(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS, block: suspend CoroutineScope.() -> T): T? { |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 154 | if (time <= 0L) return null |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 155 | return suspendCoroutineOrReturn { cont: Continuation<T?> -> |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 156 | setupTimeout(TimeoutOrNullCoroutine(time, unit, cont), block) |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 157 | } |
| 158 | } |
| 159 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 160 | /** |
| 161 | * @suppress **Deprecated**: for binary compatibility only |
| 162 | */ |
| 163 | @Deprecated("for binary compatibility only", level=DeprecationLevel.HIDDEN) |
| 164 | public suspend fun <T> withTimeoutOrNull(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS, block: suspend () -> T): T? = |
| 165 | withTimeoutOrNull(time, unit) { block() } |
| 166 | |
| 167 | private class TimeoutOrNullCoroutine<T>( |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 168 | time: Long, |
| 169 | unit: TimeUnit, |
| 170 | cont: Continuation<T?> |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 171 | ) : TimeoutCoroutine<T?, T>(time, unit, cont) { |
| 172 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | ebc8866 | 2018-01-24 23:58:56 +0300 | [diff] [blame] | 173 | internal override fun onCompletionInternal(state: Any?, mode: Int) { |
Roman Elizarov | 6640b2b | 2018-01-17 19:08:55 +0300 | [diff] [blame] | 174 | if (state is CompletedExceptionally) { |
Vsevolod Tolstopyatov | c1092d5 | 2018-04-12 20:22:25 +0300 | [diff] [blame] | 175 | val exception = state.cause |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 176 | if (exception is TimeoutCancellationException && exception.coroutine === this) |
| 177 | cont.resumeMode(null, mode) else |
| 178 | cont.resumeWithExceptionMode(exception, mode) |
| 179 | } else |
| 180 | cont.resumeMode(state as T, mode) |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 181 | } |
Roman Elizarov | daa1d9d | 2017-03-02 19:00:50 +0300 | [diff] [blame] | 182 | } |
Roman Elizarov | 507f5d4 | 2017-04-19 19:15:34 +0300 | [diff] [blame] | 183 | |
Roman Elizarov | aa461cf | 2018-04-11 13:20:29 +0300 | [diff] [blame] | 184 | /** |
| 185 | * This exception is thrown by [withTimeout] to indicate timeout. |
| 186 | */ |
| 187 | public class TimeoutCancellationException internal constructor( |
| 188 | message: String, |
| 189 | @JvmField internal val coroutine: Job? |
| 190 | ) : CancellationException(message) { |
| 191 | /** |
| 192 | * Creates timeout exception with a given message. |
| 193 | */ |
| 194 | public constructor(message: String) : this(message, null) |
| 195 | } |
| 196 | |
| 197 | @Suppress("FunctionName") |
| 198 | internal fun TimeoutCancellationException( |
| 199 | time: Long, |
| 200 | unit: TimeUnit, |
| 201 | coroutine: Job |
| 202 | ) : TimeoutCancellationException = TimeoutCancellationException("Timed out waiting for $time $unit", coroutine) |