Merge pull request #451 from InsanusMokrassar/0.21.0

0.21.0
This commit is contained in:
InsanusMokrassar 2024-06-20 01:53:51 +06:00 committed by GitHub
commit 63c8f642ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 170 additions and 107 deletions

2
.gitignore vendored
View File

@ -17,3 +17,5 @@ publishing.sh
local.* local.*
local/ local/
.kotlin/

View File

@ -1,5 +1,14 @@
# Changelog # Changelog
## 0.21.0
**THIS UPDATE CONTAINS BREAKING CHANGES IN `safely*`-ORIENTED FUNCTIONS**
* `Coroutines`:
* **All `safely` functions lost their `supervisorScope` in favor to wrapping `runCatching`**
* `runCatchingSafely` is the main handling function of all `safely` functions
* `launchSafely*` and `asyncSafely*` blocks lost `CoroutineScope` as their receiver
## 0.20.52 ## 0.20.52
* `Coroutines`: * `Coroutines`:

View File

@ -0,0 +1,44 @@
package dev.inmo.micro_utils.coroutines
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
typealias ExceptionHandler<T> = suspend (Throwable) -> T
/**
* This instance will be used in all calls of [safely] where exception handler has not been passed
*/
var defaultSafelyExceptionHandler: ExceptionHandler<Nothing> = { throw it }
/**
* This instance will be used in all calls of [safelyWithoutExceptions] as an exception handler for [safely] call
*/
var defaultSafelyWithoutExceptionHandler: ExceptionHandler<Unit> = {
try {
defaultSafelyExceptionHandler(it)
} catch (e: Throwable) {
// do nothing
}
}
/**
* This key can (and will) be used to get [ContextSafelyExceptionHandler] from [coroutineContext] of suspend functions
* and in [ContextSafelyExceptionHandler] for defining of its [CoroutineContext.Element.key]
*
* @see safelyWithContextExceptionHandler
* @see ContextSafelyExceptionHandler
*/
object ContextSafelyExceptionHandlerKey : CoroutineContext.Key<ContextSafelyExceptionHandler>
/**
* [ExceptionHandler] wrapper which was created to make possible to use [handler] across all coroutines calls
*
* @see safelyWithContextExceptionHandler
* @see ContextSafelyExceptionHandlerKey
*/
class ContextSafelyExceptionHandler(
val handler: ExceptionHandler<Unit>
) : CoroutineContext.Element {
override val key: CoroutineContext.Key<*>
get() = ContextSafelyExceptionHandlerKey
}

View File

@ -4,46 +4,58 @@ import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext import kotlin.coroutines.coroutineContext
typealias ExceptionHandler<T> = suspend (Throwable) -> T
/** /**
* This instance will be used in all calls of [safely] where exception handler has not been passed * Launching [block] in [runCatching]. In case of failure, it will:
*
* * Try to get [ContextSafelyExceptionHandler] from current [coroutineContext] and call its
* [ContextSafelyExceptionHandler.handler] invoke. **Thrown exception from its handler
* will pass out of [runCatchingSafely]**
* * Execute [onException] inside of new [runCatching] and return its result. Throws exception
* will be caught by [runCatching] and wrapped in [Result]
*
* @return [Result] with result of [block] if no exceptions or [Result] from [onException] execution
*/ */
var defaultSafelyExceptionHandler: ExceptionHandler<Nothing> = { throw it } suspend inline fun <T> runCatchingSafely(
onException: ExceptionHandler<T>,
/** block: suspend () -> T
* This instance will be used in all calls of [safelyWithoutExceptions] as an exception handler for [safely] call ): Result<T> {
*/ return runCatching {
var defaultSafelyWithoutExceptionHandler: ExceptionHandler<Unit> = { block()
try { }.onFailure {
defaultSafelyExceptionHandler(it) coroutineContext[ContextSafelyExceptionHandlerKey] ?.handler ?.invoke(it)
} catch (e: Throwable) { return runCatching {
// do nothing onException(it)
}
} }
} }
/** suspend inline fun <T, R> R.runCatchingSafely(
* This key can (and will) be used to get [ContextSafelyExceptionHandler] from [coroutineContext] of suspend functions onException: ExceptionHandler<T>,
* and in [ContextSafelyExceptionHandler] for defining of its [CoroutineContext.Element.key] block: suspend R.() -> T
* ): Result<T> = runCatchingSafely<T>(onException) {
* @see safelyWithContextExceptionHandler block()
* @see ContextSafelyExceptionHandler }
*/
object ContextSafelyExceptionHandlerKey : CoroutineContext.Key<ContextSafelyExceptionHandler>
/** /**
* [ExceptionHandler] wrapper which was created to make possible to use [handler] across all coroutines calls * Launching [runCatchingSafely] with [defaultSafelyExceptionHandler] as `onException` parameter
*
* @see safelyWithContextExceptionHandler
* @see ContextSafelyExceptionHandlerKey
*/ */
class ContextSafelyExceptionHandler( suspend inline fun <T> runCatchingSafely(
val handler: ExceptionHandler<Unit> block: suspend () -> T
) : CoroutineContext.Element { ): Result<T> = runCatchingSafely(defaultSafelyExceptionHandler, block)
override val key: CoroutineContext.Key<*>
get() = ContextSafelyExceptionHandlerKey suspend inline fun <T, R> R.runCatchingSafely(
block: suspend R.() -> T
): Result<T> = runCatchingSafely<T> {
block()
} }
//suspend inline fun <T, R> T.runCatchingSafely(
// onException: ExceptionHandler<R>,
// block: suspend T.() -> R
//): Result<R> = runCatchingSafely(onException) {
// block()
//}
/** /**
* @return [ContextSafelyExceptionHandler] from [coroutineContext] by key [ContextSafelyExceptionHandlerKey] if * @return [ContextSafelyExceptionHandler] from [coroutineContext] by key [ContextSafelyExceptionHandlerKey] if
* exists * exists
@ -64,7 +76,7 @@ suspend fun contextSafelyExceptionHandler() = coroutineContext[ContextSafelyExce
suspend fun <T> safelyWithContextExceptionHandler( suspend fun <T> safelyWithContextExceptionHandler(
contextExceptionHandler: ExceptionHandler<Unit>, contextExceptionHandler: ExceptionHandler<Unit>,
safelyExceptionHandler: ExceptionHandler<T> = defaultSafelyExceptionHandler, safelyExceptionHandler: ExceptionHandler<T> = defaultSafelyExceptionHandler,
block: suspend CoroutineScope.() -> T block: suspend () -> T
): T { ): T {
val contextSafelyExceptionHandler = contextSafelyExceptionHandler() ?.handler ?.let { oldHandler -> val contextSafelyExceptionHandler = contextSafelyExceptionHandler() ?.handler ?.let { oldHandler ->
ContextSafelyExceptionHandler { ContextSafelyExceptionHandler {
@ -78,57 +90,35 @@ suspend fun <T> safelyWithContextExceptionHandler(
} }
/** /**
* It will run [block] inside of [supervisorScope] to avoid problems with catching of exceptions * Calls [runCatchingSafely] and getting the result via [Result.getOrThrow]
* *
* Priorities of [ExceptionHandler]s: * @see runCatchingSafely
*
* * [onException] In case if custom (will be used anyway if not [defaultSafelyExceptionHandler])
* * [CoroutineContext.get] with [SafelyExceptionHandlerKey] as key
* * [defaultSafelyExceptionHandler]
*
* Remember, that [ExceptionHandler] from [CoroutineContext.get] will be used anyway if it is available. After it will
* be called [onException]
*
* @param [onException] Will be called when happen exception inside of [block]. By default will throw exception - this
* exception will be available for catching
*
* @see defaultSafelyExceptionHandler
* @see safelyWithoutExceptions
* @see safelyWithContextExceptionHandler
*/ */
suspend fun <T> safely( suspend inline fun <T> safely(
onException: ExceptionHandler<T> = defaultSafelyExceptionHandler, onException: ExceptionHandler<T>,
block: suspend CoroutineScope.() -> T block: suspend () -> T
): T { ): T = runCatchingSafely(onException, block).getOrThrow()
return try {
supervisorScope(block)
} catch (e: Throwable) {
coroutineContext[ContextSafelyExceptionHandlerKey] ?.handler ?.invoke(e)
onException(e)
}
}
suspend fun <T> runCatchingSafely( /**
onException: ExceptionHandler<T> = defaultSafelyExceptionHandler, * Calls [safely] with passing of [defaultSafelyExceptionHandler] as `onException`
block: suspend CoroutineScope.() -> T *
): Result<T> = runCatching { * @see runCatchingSafely
safely(onException, block) */
} suspend inline fun <T> safely(
block: suspend () -> T
suspend fun <T, R> T.runCatchingSafely( ): T = safely(defaultSafelyExceptionHandler, block)
onException: ExceptionHandler<R> = defaultSafelyExceptionHandler, suspend inline fun <T, R> R.safely(
block: suspend T.() -> R block: suspend R.() -> T
): Result<R> = runCatching { ): T = safely<T> { block() }
safely(onException) { block() }
}
@Deprecated("Renamed", ReplaceWith("runCatchingSafely(block)", "dev.inmo.micro_utils.coroutines.runCatchingSafely"))
suspend fun <T> safelyWithResult( suspend fun <T> safelyWithResult(
block: suspend CoroutineScope.() -> T block: suspend () -> T
): Result<T> = runCatchingSafely(defaultSafelyExceptionHandler, block) ): Result<T> = runCatchingSafely(defaultSafelyExceptionHandler, block)
@Deprecated("Renamed", ReplaceWith("this.runCatchingSafely(block)", "dev.inmo.micro_utils.coroutines.runCatchingSafely"))
suspend fun <T, R> T.safelyWithResult( suspend fun <T, R> R.safelyWithResult(
block: suspend T.() -> R block: suspend R.() -> T
): Result<R> = runCatchingSafely(defaultSafelyExceptionHandler, block) ): Result<T> = safelyWithResult<T> { block() }
/** /**
* Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and * Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and
@ -148,18 +138,20 @@ val defaultSafelyWithoutExceptionHandlerWithNull: ExceptionHandler<Nothing?> = {
* result from exception (instead of throwing it, by default always returns null) * result from exception (instead of throwing it, by default always returns null)
*/ */
suspend fun <T> safelyWithoutExceptions( suspend fun <T> safelyWithoutExceptions(
onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull, onException: ExceptionHandler<T> = defaultSafelyExceptionHandler,
block: suspend CoroutineScope.() -> T block: suspend () -> T
): T? = safely(onException, block) ): T? = runCatchingSafely(onException, block).getOrNull()
suspend fun <T> runCatchingSafelyWithoutExceptions( suspend fun <T> runCatchingSafelyWithoutExceptions(
onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull, onException: ExceptionHandler<T?> = defaultSafelyExceptionHandler,
block: suspend CoroutineScope.() -> T block: suspend () -> T
): Result<T?> = runCatching { ): Result<T?> = runCatchingSafely(onException, block).let {
safelyWithoutExceptions(onException, block) if (it.isFailure) return Result.success<T?>(null)
it
} }
fun CoroutineScope( fun CoroutineScopeWithDefaultFallback(
context: CoroutineContext, context: CoroutineContext,
defaultExceptionsHandler: ExceptionHandler<Unit> defaultExceptionsHandler: ExceptionHandler<Unit>
) = CoroutineScope( ) = CoroutineScope(

View File

@ -10,7 +10,9 @@ fun CoroutineScope.launchSafely(
onException: ExceptionHandler<Unit> = defaultSafelyExceptionHandler, onException: ExceptionHandler<Unit> = defaultSafelyExceptionHandler,
block: suspend CoroutineScope.() -> Unit block: suspend CoroutineScope.() -> Unit
) = launch(context, start) { ) = launch(context, start) {
safely(onException, block) runCatchingSafely(onException) {
block()
}
} }
fun CoroutineScope.launchSafelyWithoutExceptions( fun CoroutineScope.launchSafelyWithoutExceptions(
@ -19,7 +21,9 @@ fun CoroutineScope.launchSafelyWithoutExceptions(
onException: ExceptionHandler<Unit?> = defaultSafelyWithoutExceptionHandlerWithNull, onException: ExceptionHandler<Unit?> = defaultSafelyWithoutExceptionHandlerWithNull,
block: suspend CoroutineScope.() -> Unit block: suspend CoroutineScope.() -> Unit
) = launch(context, start) { ) = launch(context, start) {
safelyWithoutExceptions(onException, block) runCatchingSafelyWithoutExceptions(onException) {
block()
}
} }
fun <T> CoroutineScope.asyncSafely( fun <T> CoroutineScope.asyncSafely(
@ -28,7 +32,9 @@ fun <T> CoroutineScope.asyncSafely(
onException: ExceptionHandler<T> = defaultSafelyExceptionHandler, onException: ExceptionHandler<T> = defaultSafelyExceptionHandler,
block: suspend CoroutineScope.() -> T block: suspend CoroutineScope.() -> T
) = async(context, start) { ) = async(context, start) {
safely(onException, block) runCatchingSafely(onException) {
block()
}
} }
fun <T> CoroutineScope.asyncSafelyWithoutExceptions( fun <T> CoroutineScope.asyncSafelyWithoutExceptions(
@ -37,5 +43,7 @@ fun <T> CoroutineScope.asyncSafelyWithoutExceptions(
onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull, onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull,
block: suspend CoroutineScope.() -> T block: suspend CoroutineScope.() -> T
) = async(context, start) { ) = async(context, start) {
safelyWithoutExceptions(onException, block) runCatchingSafelyWithoutExceptions(onException) {
block()
}
} }

View File

@ -10,8 +10,12 @@ fun CoroutineScope.LinkedSupervisorJob(
additionalContext: CoroutineContext? = null additionalContext: CoroutineContext? = null
) = coroutineContext.LinkedSupervisorJob(additionalContext) ) = coroutineContext.LinkedSupervisorJob(additionalContext)
fun CoroutineScope.LinkedSupervisorScope(
fun CoroutineContext.LinkedSupervisorScope(
additionalContext: CoroutineContext? = null additionalContext: CoroutineContext? = null
) = CoroutineScope( ) = CoroutineScope(
coroutineContext + LinkedSupervisorJob(additionalContext) this + LinkedSupervisorJob(additionalContext)
) )
fun CoroutineScope.LinkedSupervisorScope(
additionalContext: CoroutineContext? = null
) = coroutineContext.LinkedSupervisorScope(additionalContext)

View File

@ -1,7 +1,6 @@
package dev.inmo.micro_utils.fsm.common package dev.inmo.micro_utils.fsm.common
import dev.inmo.micro_utils.common.Optional import dev.inmo.micro_utils.common.Optional
import dev.inmo.micro_utils.common.onPresented
import dev.inmo.micro_utils.coroutines.* import dev.inmo.micro_utils.coroutines.*
import dev.inmo.micro_utils.fsm.common.utils.StateHandlingErrorHandler import dev.inmo.micro_utils.fsm.common.utils.StateHandlingErrorHandler
import dev.inmo.micro_utils.fsm.common.utils.defaultStateHandlingErrorHandler import dev.inmo.micro_utils.fsm.common.utils.defaultStateHandlingErrorHandler
@ -118,23 +117,28 @@ open class DefaultStatesMachine <T: State>(
* [launchStateHandling] will returns some [State] then [statesManager] [StatesManager.update] will be used, otherwise * [launchStateHandling] will returns some [State] then [statesManager] [StatesManager.update] will be used, otherwise
* [StatesManager.endChain]. * [StatesManager.endChain].
*/ */
override fun start(scope: CoroutineScope): Job = scope.launchSafelyWithoutExceptions { override fun start(scope: CoroutineScope): Job {
(statesManager.getActiveStates().asFlow() + statesManager.onStartChain).subscribeSafelyWithoutExceptions(this) { val supervisorScope = scope.LinkedSupervisorScope()
launch { performStateUpdate(Optional.absent(), it, scope.LinkedSupervisorScope()) } supervisorScope.launchSafelyWithoutExceptions {
} (statesManager.getActiveStates().asFlow() + statesManager.onStartChain).subscribeSafelyWithoutExceptions(supervisorScope) {
statesManager.onChainStateUpdated.subscribeSafelyWithoutExceptions(this) { supervisorScope.launch { performStateUpdate(Optional.absent(), it, supervisorScope) }
launch { performStateUpdate(Optional.presented(it.first), it.second, scope.LinkedSupervisorScope()) } }
} statesManager.onChainStateUpdated.subscribeSafelyWithoutExceptions(supervisorScope) {
statesManager.onEndChain.subscribeSafelyWithoutExceptions(this) { removedState -> supervisorScope.launch { performStateUpdate(Optional.presented(it.first), it.second, supervisorScope) }
launch { }
statesJobsMutex.withLock { statesManager.onEndChain.subscribeSafelyWithoutExceptions(supervisorScope) { removedState ->
val stateInMap = statesJobs.keys.firstOrNull { stateInMap -> stateInMap == removedState } supervisorScope.launch {
if (stateInMap === removedState) { statesJobsMutex.withLock {
statesJobs[stateInMap] ?.cancel() val stateInMap = statesJobs.keys.firstOrNull { stateInMap -> stateInMap == removedState }
if (stateInMap === removedState) {
statesJobs[stateInMap] ?.cancel()
}
} }
} }
} }
} }
return supervisorScope.coroutineContext.job
} }
/** /**

View File

@ -15,5 +15,5 @@ crypto_js_version=4.1.1
# Project data # Project data
group=dev.inmo group=dev.inmo
version=0.20.52 version=0.21.0
android_code_version=258 android_code_version=259

View File

@ -41,7 +41,7 @@ class TemporalFilesRoutingConfigurator(
filesMutex: Mutex, filesMutex: Mutex,
onNewFileFlow: Flow<TemporalFileId> onNewFileFlow: Flow<TemporalFileId>
): Job = scope.launchSafelyWithoutExceptions { ): Job = scope.launchSafelyWithoutExceptions {
while (isActive) { while (currentCoroutineContext().isActive) {
val filesWithCreationInfo = filesMap.mapNotNull { (fileId, file) -> val filesWithCreationInfo = filesMap.mapNotNull { (fileId, file) ->
fileId to ((Files.getAttribute(file.toPath(), "creationTime") as? FileTime) ?.toMillis() ?: return@mapNotNull null) fileId to ((Files.getAttribute(file.toPath(), "creationTime") as? FileTime) ?.toMillis() ?: return@mapNotNull null)
} }