diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f7002dd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: Validation + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: validation-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + validate: + # iOS targets build only on macOS + runs-on: macos-latest + timeout-minutes: 90 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Run tests and assemble + run: ./gradlew --no-daemon --stacktrace :library:allTests :library:assemble diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8793859 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,88 @@ +name: Release Library + +on: + push: + tags: + - 'v*' + +permissions: + contents: read + packages: write + +jobs: + publish-library: + # iOS klibs can only be built and published from macOS + runs-on: macos-latest + environment: release + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Run tests + run: | + ./gradlew --no-daemon --stacktrace \ + :library:allTests + + - name: Validate tag matches version + run: | + TAG="${GITHUB_REF#refs/tags/}" + VERSION=$(grep '^versionName=' gradle.properties | cut -d'=' -f2) + if [ "v${VERSION}" != "${TAG}" ] && [ "${VERSION}" != "${TAG}" ]; then + echo "Tag '${TAG}' does not match versionName '${VERSION}' in gradle.properties" + exit 1 + fi + + - name: Prepare publishing credentials + env: + NEXUS_USERTOKEN_NAME: ${{ secrets.NEXUS_USERTOKEN_NAME }} + NEXUS_USERTOKEN_PASSWORD: ${{ secrets.NEXUS_USERTOKEN_PASSWORD }} + SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }} + SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} + SIGNING_SECRET_KEY_RING_FILE_BASE64: ${{ secrets.SIGNING_SECRET_KEY_RING_FILE_BASE64 }} + run: | + required_vars=( + NEXUS_USERTOKEN_NAME + NEXUS_USERTOKEN_PASSWORD + SIGNING_KEY_ID + SIGNING_PASSWORD + SIGNING_SECRET_KEY_RING_FILE_BASE64 + ) + + for var in "${required_vars[@]}"; do + if [ -z "${!var}" ]; then + echo "Missing required secret: ${var}" + exit 1 + fi + done + + keyring_file="${RUNNER_TEMP}/signing-secring.gpg" + echo "${SIGNING_SECRET_KEY_RING_FILE_BASE64}" | base64 --decode > "${keyring_file}" + chmod 600 "${keyring_file}" + + mkdir -p "${HOME}/.gradle" + { + echo "mavenCentralUsername=${NEXUS_USERTOKEN_NAME}" + echo "mavenCentralPassword=${NEXUS_USERTOKEN_PASSWORD}" + echo "NEXUS_USERTOKEN_NAME=${NEXUS_USERTOKEN_NAME}" + echo "NEXUS_USERTOKEN_PASSWORD=${NEXUS_USERTOKEN_PASSWORD}" + echo "signing.keyId=${SIGNING_KEY_ID}" + echo "signing.password=${SIGNING_PASSWORD}" + echo "signing.secretKeyRingFile=${keyring_file}" + } >> "${HOME}/.gradle/gradle.properties" + + - name: Publish library + run: | + ./gradlew --no-daemon --stacktrace \ + :library:publishAndReleaseToMavenCentral diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..459fd76 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## 1.0.0 - 2026-11-08 + +First public release, published to Maven Central as `ru.kode:reactive-tasks`. + +- Kotlin Multiplatform targets: JVM, Android, iOS (`iosX64`, `iosArm64`, `iosSimulatorArm64`). diff --git a/README.md b/README.md index 88e1b05..75ff4d6 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,14 @@ A library for scheduling, executing and observing repeateble reactive tasks. +# Installation + +Kotlin Multiplatform: JVM, Android, iOS (`iosX64`, `iosArm64`, `iosSimulatorArm64`). + +```kotlin +implementation("ru.kode:reactive-tasks:1.0.0") +``` + # How to use ```kotlin diff --git a/gradle.properties b/gradle.properties index 5e4d56d..0e31d6e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,3 +10,17 @@ kotlin.mpp.enableCInteropCommonization=true #Android android.useAndroidX=true android.nonTransitiveRClass=true +#Publishing +versionName=1.0.0 +pomGroupId=ru.kode +pomName=Reactive Tasks +pomDescription=Kotlin Multiplatform library for scheduling, executing and observing reactive tasks +pomUrl=https://github.com/appKODE/reactive-tasks +pomScmUrl=https://github.com/appKODE/reactive-tasks +pomScmConnection=scm:git:https://github.com/appKODE/reactive-tasks.git +pomScmDevConnection=scm:git:ssh://github.com/appKODE/reactive-tasks.git +pomLicenseName=MIT License +pomLicenseUrl=https://opensource.org/licenses/MIT +pomLicenseDist=repo +pomDeveloperId=dimsuz +pomDeveloperName=Dmitry Suzdalev diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ffe791a..8210c02 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,14 +1,17 @@ [versions] -agp = "8.13.0" -kotlin = "2.2.20" +agp = "9.0.1" +kotlin = "2.3.20" android-minSdk = "24" android-compileSdk = "36" -vanniktechMavenPublish = "0.34.0" +vanniktechMavenPublish = "0.37.0" coroutines = "1.10.2" +atomicfu = "0.29.0" [libraries] kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } +kotlin-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } +kotlinx-atomicfu = { module = "org.jetbrains.kotlinx:atomicfu", version.ref = "atomicfu" } [plugins] android-kotlin-multiplatform-library = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index d4081da..c61a118 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 298f7a8..4e7db10 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -1,4 +1,3 @@ -import com.android.build.api.dsl.androidLibrary import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { @@ -7,35 +6,25 @@ plugins { alias(libs.plugins.vanniktech.mavenPublish) } -group = "ru.kode.reactivetasks" -version = "1.0.0" +group = providers.gradleProperty("pomGroupId").get() +version = providers.gradleProperty("versionName").get() kotlin { jvm() - androidLibrary { + android { namespace = "ru.kode.reactivetasks" compileSdk = libs.versions.android.compileSdk.get().toInt() minSdk = libs.versions.android.minSdk.get().toInt() - // withJava() // enable java compilation support + withHostTest {} - withHostTestBuilder {}.configure {} - // withDeviceTestBuilder { - // sourceSetTreeName = "test" - // } - - compilations.configureEach { - compilerOptions.configure { - jvmTarget.set( - JvmTarget.JVM_17 - ) - } + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) } } iosX64() iosArm64() iosSimulatorArm64() - // linuxX64() sourceSets { commonMain.dependencies { @@ -44,40 +33,57 @@ kotlin { commonTest.dependencies { implementation(libs.kotlin.test) + implementation(libs.kotlin.coroutines.test) + } + + iosMain.dependencies { + implementation(libs.kotlinx.atomicfu) } } } mavenPublishing { - publishToMavenCentral() + coordinates(artifactId = "reactive-tasks") + publishToMavenCentral() signAllPublications() - coordinates(group.toString(), "library", version.toString()) - pom { - name = "My library" - description = "A library." - inceptionYear = "2024" - url = "https://github.com/appkode/my-library" + val pomName: String by project + val pomDescription: String by project + val pomUrl: String by project + val pomScmUrl: String by project + val pomScmConnection: String by project + val pomScmDevConnection: String by project + val pomLicenseName: String by project + val pomLicenseUrl: String by project + val pomLicenseDist: String by project + val pomDeveloperId: String by project + val pomDeveloperName: String by project + + name.set(pomName) + description.set(pomDescription) + url.set(pomUrl) + + scm { + url.set(pomScmUrl) + connection.set(pomScmConnection) + developerConnection.set(pomScmDevConnection) + } + licenses { license { - name = "XXX" - url = "YYY" - distribution = "ZZZ" + name.set(pomLicenseName) + url.set(pomLicenseUrl) + distribution.set(pomLicenseDist) } } + developers { developer { - id = "XXX" - name = "YYY" - url = "ZZZ" + id.set(pomDeveloperId) + name.set(pomDeveloperName) } } - scm { - url = "XXX" - connection = "YYY" - developerConnection = "ZZZ" - } } } diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ConcurrentCollectionsTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ConcurrentCollectionsTest.kt new file mode 100644 index 0000000..8042660 --- /dev/null +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ConcurrentCollectionsTest.kt @@ -0,0 +1,99 @@ +package ru.kode.reactivetasks + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class ConcurrentCollectionsTest { + + @Test + fun mapBasicOperations() { + val map = createConcurrentMutableMap() + + assertNull(map.put("a", 1)) + assertEquals(1, map["a"]) + assertEquals(1, map.put("a", 2)) + assertEquals(2, map["a"]) + map["b"] = 3 + assertEquals(2, map.size) + assertTrue(map.containsKey("b")) + assertEquals(3, map.remove("b")) + assertFalse(map.containsKey("b")) + assertNull(map["b"]) + assertEquals(1, map.size) + } + + @Test + fun mapEntriesIterationToleratesPuts() { + val map = createConcurrentMutableMap() + repeat(10) { map[it] = it } + + for ((key, _) in map.entries) { + map[key + 100] = key + } + + assertTrue(map.size >= 10) + } + + @Test + fun listBasicOperations() { + val list = createConcurrentMutableList() + + list.add("a") + list.add("b") + list.add("c") + assertEquals(3, list.size) + assertEquals("b", list[1]) + assertEquals("b", list.set(1, "B")) + assertEquals(listOf("a", "B", "c"), list.toList()) + assertTrue(list.remove("a")) + assertFalse(list.remove("missing")) + assertEquals("c", list.removeAt(1)) + assertEquals(listOf("B"), list.toList()) + } + + @Test + fun listIterationSeesSnapshot() { + val list = createConcurrentMutableList() + list.addAll(listOf(1, 2, 3)) + val seen = mutableListOf() + + list.forEach { + seen += it + list.add(it * 10) + list.remove(it) + } + + assertEquals(listOf(1, 2, 3), seen) + assertEquals(listOf(10, 20, 30), list.toList()) + } + + @Test + fun concurrentWritesAreNotLost() = runTest { + val map = createConcurrentMutableMap() + val list = createConcurrentMutableList() + + withContext(Dispatchers.Default) { + coroutineScope { + repeat(8) { worker -> + launch { + repeat(1000) { i -> + map[worker * 1000 + i] = i + list.add(i) + } + } + } + } + } + + assertEquals(8000, map.size) + assertEquals(8000, list.size) + } +} diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt new file mode 100644 index 0000000..c0de13f --- /dev/null +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -0,0 +1,114 @@ +@file:OptIn(ExperimentalUuidApi::class, ExperimentalCoroutinesApi::class) + +package ru.kode.reactivetasks + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.uuid.ExperimentalUuidApi + +class ObserveStateChangesTest { + + private class Collected(val job: Job) { + val states = mutableListOf() + var error: Throwable? = null + } + + private fun TestScope.collect(flow: Flow): Collected { + lateinit var collected: Collected + // unconfined: advanceUntilIdle() does not run backgroundScope work, so the collector must resume eagerly + val job = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + try { + flow.collect { collected.states += it } + } catch (e: CancellationException) { + collected.error = e + throw e + } + } + collected = Collected(job) + runCurrent() // subscribe before the test starts anything + return collected + } + + @Test + fun emitsRunningThenSuccess() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { s: String -> s.uppercase() } + val collected = collect(scheduler.observeStateChanges(task)) + + val job = scheduler.start(task, "a") + advanceUntilIdle() + + assertEquals(listOf(RunState.Running, RunState.FinishedSuccess), collected.states.map { it.runState }) + assertTrue(collected.states.all { it.jobId == job.id }) + assertEquals("A", collected.states.last().result) + assertNull(collected.error) + } + + @Test + fun cancellingCollectorRemovesListener() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("t") { _: Int -> } + val collected = collect(scheduler.observeStateChanges(task)) + // added after the flow's listener: if the dead listener were still there, its send would throw + // and abort the job before this one is notified + val plain = RecordingListener().also(scheduler::addTaskStateChangeListener) + + collected.job.cancel() + advanceUntilIdle() + scheduler.start(task, 1) + advanceUntilIdle() + + assertTrue(collected.states.isEmpty()) + assertEquals(listOf(RunState.Running, RunState.FinishedSuccess), plain.states.map { it.runState }) + assertTrue(plain.cancelled.isEmpty()) + } + + @Test + fun jobCancellationClosesFlow() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val collected = collect(scheduler.observeStateChanges(task)) + + val job = scheduler.start(task, 1) + runCurrent() + scheduler.cancel(job) + advanceUntilIdle() + + assertEquals(listOf(RunState.Running), collected.states.map { it.runState }) + val error = assertIs(collected.error) + assertTrue(error.message.orEmpty().contains("jobId=${job.id} was cancelled"), error.message) + assertTrue(collected.job.isCompleted) + } + + @Test + fun emitsStatesOfOtherTasks() = runTest { + val scheduler = testScheduler() + val observed = scheduler.registerTask("observed") { _: Int -> } + val other = scheduler.registerTask("other") { _: Int -> delay(1000) } + val collected = collect(scheduler.observeStateChanges(observed)) + + // quirk: no filtering by handle, other tasks' states leak into the flow... + val otherJob = scheduler.start(other, 1) + runCurrent() + assertEquals(listOf(other.id), collected.states.map { it.taskId }) + + // ...and cancelling another task closes it + scheduler.cancel(otherJob) + advanceUntilIdle() + assertIs(collected.error) + } +} diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ReactiveTasksTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ReactiveTasksTest.kt deleted file mode 100644 index 292254d..0000000 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ReactiveTasksTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -@file:OptIn(ExperimentalUuidApi::class) -package ru.kode.reactivetasks - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlin.test.Test -import kotlin.test.assertNotNull -import kotlin.uuid.ExperimentalUuidApi - -class ReactiveTasksTest { - - @Test - fun shouldCreateTaskHandle() { - val scope = CoroutineScope(Dispatchers.Default) - val scheduler = Scheduler(scope = scope) - - val taskHandle = scheduler.registerTask("fetch") { userId: String -> - delay(1000) - } - - assertNotNull(taskHandle) - } - -} diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt new file mode 100644 index 0000000..466577b --- /dev/null +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt @@ -0,0 +1,466 @@ +@file:OptIn(ExperimentalUuidApi::class, ExperimentalCoroutinesApi::class) + +package ru.kode.reactivetasks + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.coroutines.ContinuationInterceptor +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue +import kotlin.uuid.ExperimentalUuidApi +import kotlin.uuid.Uuid + +internal sealed interface Event { + data class Changed(val state: JobState) : Event + data class Cancelled(val taskId: Uuid, val jobId: Uuid) : Event +} + +internal class RecordingListener : TaskStateChangeListener { + val events = mutableListOf() + + val states: List get() = events.filterIsInstance().map { it.state } + val cancelled: List get() = events.filterIsInstance() + + override suspend fun onJobStateChanged(state: JobState) { + events += Event.Changed(state) + } + + override fun onJobCancelled(taskId: Uuid, jobId: Uuid) { + events += Event.Cancelled(taskId, jobId) + } +} + +internal class UncaughtRecorder { + val errors = mutableListOf>() + val handler: (Uuid, String, Throwable) -> Unit = { id, name, e -> errors += Triple(id, name, e) } +} + +internal fun TestScope.testScheduler(uncaught: UncaughtRecorder = UncaughtRecorder()) = Scheduler( + scope = backgroundScope, + defaultDispatcher = StandardTestDispatcher(testScheduler), + onUncaughtException = uncaught.handler, +) + +class SchedulerTest { + + // region registerTask / handles + + @Test + fun registerTaskReturnsNamedHandleWithUniqueId() = runTest { + val scheduler = testScheduler() + val a = scheduler.registerTask("fetch") { _: String -> } + val b = scheduler.registerTask("fetch") { _: String -> } + + assertEquals("fetch", a.name) + assertNotEquals(a.id, b.id) + assertNotEquals(Uuid.NIL, a.id) + assertEquals("TaskHandle[name=fetch,id=${a.id}]", a.toString()) + + val job = scheduler.start(a, "x") + assertEquals("JobHandle[id=${job.id}]", job.toString()) + assertSame(a, job.taskHandle) + } + + @Test + fun nilToStrings() { + assertEquals("TaskHandle.NIL", TaskHandle.NIL.toString()) + assertEquals("JobHandle.NIL", JobHandle.NIL.toString()) + assertEquals("JobState.NIL", JobState.NIL.toString()) + } + + @Test + fun bodyRunsOnGivenDispatcherOrDefault() = runTest { + val scheduler = testScheduler() + val custom = StandardTestDispatcher(testScheduler, name = "custom") + var seenCustom: ContinuationInterceptor? = null + var seenDefault: ContinuationInterceptor? = null + val onCustom = scheduler.registerTask("custom", custom) { _: Unit -> + seenCustom = currentCoroutineContext()[ContinuationInterceptor] + } + val onDefault = scheduler.registerTask("default") { _: Unit -> + seenDefault = currentCoroutineContext()[ContinuationInterceptor] + } + + scheduler.start(onCustom, Unit) + scheduler.start(onDefault, Unit) + advanceUntilIdle() + + assertSame(custom, seenCustom) + assertSame(scheduler.defaultDispatcher, seenDefault) + } + + // endregion + + // region start + + @Test + fun startReportsRunningThenSuccess() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("len") { s: String -> delay(100); s.length } + + val job = scheduler.start(task, "abc", tag = "t") + advanceUntilIdle() + + val running = JobState(job.id, task.id, "abc", RunState.Running, tag = "t") + val success = JobState(job.id, task.id, "abc", RunState.FinishedSuccess, result = 3, tag = "t") + assertEquals(listOf(Event.Changed(running), Event.Changed(success)), listener.events) + assertEquals(success, scheduler.taskJobState[job.id]) + assertEquals(job.id, listener.states.first().jobId) + } + + @Test + fun bodyExceptionBecomesFinishedError() = runTest { + val uncaught = UncaughtRecorder() + val scheduler = testScheduler(uncaught) + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val boom = IllegalStateException("boom") + val task = scheduler.registerTask("fail") { throw boom } + + val job = scheduler.start(task, Unit) + advanceUntilIdle() + + assertEquals(listOf(RunState.Running, RunState.FinishedError), listener.states.map { it.runState }) + val final = scheduler.taskJobState.getValue(job.id) + assertSame(boom, final.error) + assertNull(final.result) + assertTrue(uncaught.errors.isEmpty()) + assertTrue(listener.cancelled.isEmpty()) + } + + @Test + fun twoStartsRunConcurrently() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(100) } + + val first = scheduler.start(task, 1) + val second = scheduler.start(task, 2) + runCurrent() + assertEquals(RunState.Running, scheduler.taskJobState.getValue(first.id).runState) + assertEquals(RunState.Running, scheduler.taskJobState.getValue(second.id).runState) + + advanceUntilIdle() + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(first.id).runState) + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(second.id).runState) + } + + @Test + fun listenerExceptionGoesToOnUncaughtException() = runTest { + val uncaught = UncaughtRecorder() + val scheduler = testScheduler(uncaught) + val listener = RecordingListener() + scheduler.addTaskStateChangeListener(object : TaskStateChangeListener { + override suspend fun onJobStateChanged(state: JobState) = throw IllegalStateException("listener") + override fun onJobCancelled(taskId: Uuid, jobId: Uuid) = Unit + }) + scheduler.addTaskStateChangeListener(listener) + val task = scheduler.registerTask("named") { _: Unit -> } + + scheduler.start(task, Unit) + advanceUntilIdle() + + val (id, name, error) = uncaught.errors.single() + assertEquals(task.id, id) + assertEquals("named", name) + assertIs(error) + assertEquals("listener", error.message) + // the throwing listener aborts the job before later listeners are notified + assertTrue(listener.events.isEmpty()) + } + + // endregion + + // region startLatest + + @Test + fun startLatestCancelsPreviousJob() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("search") { q: String -> delay(1000); q } + + val first = scheduler.start(task, "a") + runCurrent() + val second = scheduler.startLatest(task, "ab") + advanceUntilIdle() + + assertEquals( + listOf( + Event.Changed(JobState(first.id, task.id, "a", RunState.Running)), + Event.Cancelled(task.id, first.id), + Event.Changed(JobState(second.id, task.id, "ab", RunState.Running)), + Event.Changed(JobState(second.id, task.id, "ab", RunState.FinishedSuccess, result = "ab")), + ), + listener.events, + ) + assertTrue(first.job.isCancelled) + // quirk: a cancelled job's state stays Running forever + assertEquals(RunState.Running, scheduler.taskJobState.getValue(first.id).runState) + } + + // endregion + + // region startSuspended + + @Test + fun startSuspendedReturnsFinalState() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val boom = IllegalArgumentException("bad") + val task = scheduler.registerTask("parse") { s: String -> if (s == "bad") throw boom else s.toInt() } + + val ok = scheduler.startSuspended(task, "42", tag = "t") + assertEquals(RunState.FinishedSuccess, ok.runState) + assertEquals(42, ok.result) + assertEquals("t", ok.tag) + assertEquals(ok, scheduler.taskJobState[ok.jobId]) + + val failed = scheduler.startSuspended(task, "bad") + assertEquals(RunState.FinishedError, failed.runState) + assertSame(boom, failed.error) + + assertEquals( + listOf(RunState.Running, RunState.FinishedSuccess, RunState.Running, RunState.FinishedError), + listener.states.map { it.runState }, + ) + } + + @Test + fun startSuspendedCancellationThrowsWithoutOnJobCancelled() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("slow") { _: Unit -> delay(1000) } + var thrown: Throwable? = null + + val caller = launch { + try { + scheduler.startSuspended(task, Unit) + } catch (e: CancellationException) { + thrown = e + throw e + } + } + runCurrent() + caller.cancel() + advanceUntilIdle() + + assertIs(thrown) + assertTrue(caller.isCancelled) + assertEquals(listOf(RunState.Running), listener.states.map { it.runState }) + assertTrue(listener.cancelled.isEmpty()) + } + + // endregion + + // region restart + + @Test + fun restartTaskReusesMostRecentArgumentAndDropsTag() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("echo") { s: String -> s } + + scheduler.start(task, "a", tag = "t") + val r1 = scheduler.restart(task) + advanceUntilIdle() + assertEquals("a", scheduler.taskJobState.getValue(r1.id).result) + assertNull(scheduler.taskJobState.getValue(r1.id).tag) + + scheduler.startLatest(task, "b", tag = "t") + val r2 = scheduler.restart(task) + advanceUntilIdle() + assertEquals("b", scheduler.taskJobState.getValue(r2.id).argument) + + scheduler.startSuspended(task, "c", tag = "t") + val r3 = scheduler.restart(task) + advanceUntilIdle() + assertEquals("c", scheduler.taskJobState.getValue(r3.id).argument) + assertNull(scheduler.taskJobState.getValue(r3.id).tag) + } + + @Test + fun restartJobReusesThatJobsArgument() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("echo") { s: String -> s } + + val first = scheduler.start(task, "first") + scheduler.start(task, "second") + val restarted = scheduler.restart(first) + advanceUntilIdle() + + assertNotEquals(first.id, restarted.id) + assertSame(task, restarted.taskHandle) + assertEquals("first", scheduler.taskJobState.getValue(restarted.id).result) + } + + @Test + fun restartWithoutPreviousStartReturnsNil() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("never") { _: String -> } + + assertSame(JobHandle.NIL, scheduler.restart(task)) + assertSame(JobHandle.NIL, scheduler.restart(JobHandle.NIL)) + } + + @Test + fun restartAfterNullArgument() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("nullable") { _: String? -> } + + val started = runCatching { scheduler.start(task, null) } + // quirk: JVM/Android argumentCache is a ConcurrentHashMap, which rejects null values, so start throws NPE. + // iOS LockedMap accepts null, but restart treats a null argument as "never started" and returns NIL. + val error = started.exceptionOrNull() + if (error != null) { + assertIs(error) + } else { + assertSame(JobHandle.NIL, scheduler.restart(task)) + assertSame(JobHandle.NIL, scheduler.restart(started.getOrThrow())) + } + } + + // endregion + + // region cancel / cancelAndJoin + + @Test + fun cancelTaskCancelsAllItsJobsOnly() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + val other = scheduler.registerTask("other") { _: Int -> delay(1000) } + + val a = scheduler.start(task, 1) + val b = scheduler.start(task, 2) + val c = scheduler.start(other, 3) + runCurrent() + scheduler.cancel(task) + advanceUntilIdle() + + assertEquals(setOf(Event.Cancelled(task.id, a.id), Event.Cancelled(task.id, b.id)), listener.cancelled.toSet()) + assertEquals(2, listener.cancelled.size) + assertTrue(a.job.isCancelled && b.job.isCancelled) + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(c.id).runState) + } + + @Test + fun cancelJobCancelsOnlyThatJob() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + + val a = scheduler.start(task, 1) + val b = scheduler.start(task, 2) + runCurrent() + scheduler.cancel(a) + advanceUntilIdle() + + assertEquals(listOf(Event.Cancelled(task.id, a.id)), listener.cancelled) + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(b.id).runState) + } + + @Test + fun cancelAndJoinTaskWaitsForCompletion() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + + val a = scheduler.start(task, 1) + val b = scheduler.start(task, 2) + runCurrent() + scheduler.cancelAndJoin(task) + + assertTrue(a.job.isCancelled && a.job.isCompleted) + assertTrue(b.job.isCancelled && b.job.isCompleted) + } + + @Test + fun cancelAndJoinJobWaitsForCompletion() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + + val a = scheduler.start(task, 1) + val b = scheduler.start(task, 2) + runCurrent() + scheduler.cancelAndJoin(a) + + assertTrue(a.job.isCancelled && a.job.isCompleted) + assertTrue(b.job.isActive) + } + + @Test + fun cancellingSchedulerScopeCancelsJobs() = runTest { + val parent = Job() + val scheduler = Scheduler(CoroutineScope(parent), StandardTestDispatcher(testScheduler), UncaughtRecorder().handler) + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("slow") { _: Int -> delay(1000) } + + val job = scheduler.start(task, 1) + runCurrent() + parent.cancel() + advanceUntilIdle() + + assertTrue(job.job.isCancelled) + assertEquals(listOf(Event.Cancelled(task.id, job.id)), listener.cancelled) + } + + // endregion + + // region listeners + + @Test + fun removedListenerGetsNoMoreEvents() = runTest { + val scheduler = testScheduler() + val listener = RecordingListener().also(scheduler::addTaskStateChangeListener) + val task = scheduler.registerTask("t") { _: Int -> } + + scheduler.start(task, 1) + advanceUntilIdle() + scheduler.removeTaskStateChangeListener(listener) + scheduler.start(task, 2) + advanceUntilIdle() + + assertEquals(listOf(1, 1), listener.states.map { it.argument }) + } + + @Test + fun mutatingListenersInsideCallbackIsSafe() = runTest { + val scheduler = testScheduler() + val late = RecordingListener() + val selfRemoving = object : TaskStateChangeListener { + var calls = 0 + override suspend fun onJobStateChanged(state: JobState) { + calls++ + scheduler.removeTaskStateChangeListener(this) + scheduler.addTaskStateChangeListener(late) + } + override fun onJobCancelled(taskId: Uuid, jobId: Uuid) = Unit + } + val bystander = RecordingListener() + scheduler.addTaskStateChangeListener(selfRemoving) + scheduler.addTaskStateChangeListener(bystander) + val task = scheduler.registerTask("t") { _: Int -> } + + scheduler.start(task, 1) + advanceUntilIdle() + + assertEquals(1, selfRemoving.calls) + assertEquals(listOf(RunState.Running, RunState.FinishedSuccess), bystander.states.map { it.runState }) + // added during the Running dispatch: misses that snapshot, sees the next one + assertEquals(listOf(RunState.FinishedSuccess), late.states.map { it.runState }) + } + + // endregion +} diff --git a/library/src/iosMain/kotlin/ru/kode/reactivetasks/ReactiveTasksIos.kt b/library/src/iosMain/kotlin/ru/kode/reactivetasks/ReactiveTasksIos.kt new file mode 100644 index 0000000..7d8b176 --- /dev/null +++ b/library/src/iosMain/kotlin/ru/kode/reactivetasks/ReactiveTasksIos.kt @@ -0,0 +1,80 @@ +package ru.kode.reactivetasks + +import kotlinx.atomicfu.locks.SynchronizedObject +import kotlinx.atomicfu.locks.synchronized +import kotlin.concurrent.Volatile + +actual fun createConcurrentMutableMap(): MutableMap { + return LockedMap() +} + +actual fun createConcurrentMutableList(): MutableList { + return CopyOnWriteList() +} + +/** + * HashMap guarded by a single lock. [entries], [keys] and [values] return snapshot copies, + * so iterating them never observes a concurrent modification. + */ +// ponytail: one lock for the whole map, fine for the handful of tasks a ReactiveTasks instance holds +private class LockedMap : MutableMap { + private val lock = SynchronizedObject() + private val map = HashMap() + + override val size: Int get() = synchronized(lock) { map.size } + override fun isEmpty(): Boolean = synchronized(lock) { map.isEmpty() } + override fun containsKey(key: K): Boolean = synchronized(lock) { map.containsKey(key) } + override fun containsValue(value: V): Boolean = synchronized(lock) { map.containsValue(value) } + override fun get(key: K): V? = synchronized(lock) { map[key] } + override fun put(key: K, value: V): V? = synchronized(lock) { map.put(key, value) } + override fun remove(key: K): V? = synchronized(lock) { map.remove(key) } + override fun putAll(from: Map) = synchronized(lock) { map.putAll(from) } + override fun clear() = synchronized(lock) { map.clear() } + + override val entries: MutableSet> + get() = synchronized(lock) { HashMap(map).entries } + override val keys: MutableSet + get() = synchronized(lock) { map.keys.toMutableSet() } + override val values: MutableCollection + get() = synchronized(lock) { map.values.toMutableList() } + + override fun equals(other: Any?): Boolean = synchronized(lock) { map == other } + override fun hashCode(): Int = synchronized(lock) { map.hashCode() } + override fun toString(): String = synchronized(lock) { map.toString() } +} + +/** Same semantics as java.util.concurrent.CopyOnWriteArrayList: iterators work on a snapshot. */ +private class CopyOnWriteList : AbstractMutableList() { + private val lock = SynchronizedObject() + + @Volatile + private var items: List = emptyList() + + override val size: Int get() = items.size + override fun get(index: Int): T = items[index] + override fun iterator(): MutableIterator = SnapshotIterator(items.iterator()) + + override fun add(index: Int, element: T) = synchronized(lock) { + items = items.toMutableList().apply { add(index, element) } + } + + override fun set(index: Int, element: T): T = synchronized(lock) { + val copy = items.toMutableList() + copy.set(index, element).also { items = copy } + } + + override fun removeAt(index: Int): T = synchronized(lock) { + val copy = items.toMutableList() + copy.removeAt(index).also { items = copy } + } + + // base class would remove through iterator(), which is a read-only snapshot here + override fun remove(element: T): Boolean = synchronized(lock) { + val copy = items.toMutableList() + copy.remove(element).also { if (it) items = copy } + } + + private class SnapshotIterator(private val delegate: Iterator) : MutableIterator, Iterator by delegate { + override fun remove() = throw UnsupportedOperationException() + } +}