diff --git a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImpl.kt b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImpl.kt index 5068175837..ec9e63efb0 100644 --- a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImpl.kt +++ b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImpl.kt @@ -64,8 +64,10 @@ import org.gradle.tooling.internal.consumer.DefaultGradleConnector import org.jetbrains.annotations.VisibleForTesting import org.slf4j.LoggerFactory import java.io.File +import java.util.Properties import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock @@ -79,9 +81,24 @@ internal class ToolingApiServerImpl( { onStarted, onExited -> GradleDaemonWatcher(onStarted = onStarted, onExited = onExited) }, ) : IToolingApiServer { private var client: IToolingApiClient? = null + + // Volatile because the reuse decision crosses threads: each initialize() runs on whichever + // commonPool worker CompletableFuture.supplyAsync hands it, and nothing else in this class + // establishes a happens-before edge between one call's writes and the next call's reads. A + // stale null read here reintroduces ADFA-5589 intermittently. + @Volatile private var connector: GradleConnector? = null + + @Volatile private var connection: ProjectConnection? = null - private var lastInitParams: InitializeProjectParams? = null + + @Volatile + @VisibleForTesting + internal var lastInitParams: InitializeProjectParams? = null + + /** The `distributionUrl` the wrapper named when [connection] was opened; null if not a wrapper. */ + @Volatile + private var lastWrapperDistribution: String? = null @Suppress("ktlint:standard:backing-property-naming") private var _buildCancellationToken: CancellationTokenSource? = null @@ -92,20 +109,110 @@ internal class ToolingApiServerImpl( set(value) = cancellationTokenAccessLock.withLock { _buildCancellationToken = value } /** Whether the project has been initialized or not. */ + @Volatile var isInitialized: Boolean = false private set - /** Whether a build or project synchronization is in progress. */ - private var isBuildInProgress: Boolean = false + /** + * Whether a build or project synchronization is in progress, as a CAS rather than a + * read-then-write. + * + * Same reason the fields above are @Volatile: every call runs on whichever commonPool worker + * CompletableFuture.supplyAsync hands it. As a plain Boolean, two concurrent executeTasks calls + * could both read false and both proceed -- two builds against one connection and one + * cancellation token -- and a worker could go on seeing a stale true and refuse every build for + * the life of the server. ([buildCancellationToken] needs nothing here; it already reads and + * writes under its own lock.) + */ + private val buildInProgress = AtomicBoolean(false) /** Whether the server has a live connection to Gradle. */ val isConnected: Boolean get() = connector != null || connection != null companion object { + private const val WRAPPER_PROPERTIES = "gradle/wrapper/gradle-wrapper.properties" + private val log = LoggerFactory.getLogger(ToolingApiServerImpl::class.java) + + /** + * Whether [a] and [b] name the same connection: the same project directory, served by the + * same Gradle distribution. A connector is bound to those two and nothing else; every other + * field of [InitializeProjectParams] is per-call. + * + * `a == b` cannot stand in for this. [InitializeProjectParams] declares no `equals`, so that + * is reference equality between objects that arrive freshly deserialized on every call, and + * it answered false every time (ADFA-5589). + */ + @VisibleForTesting + internal fun describesSameConnection( + a: InitializeProjectParams?, + b: InitializeProjectParams, + ): Boolean = + a != null && + sameDirectory(a.directory, b.directory) && + a.gradleDistribution == b.gradleDistribution + + /** + * Whether [a] and [b] name the same directory. + * + * As paths, not as strings: `GradleConnector.forProjectDirectory` takes a [File], so a + * trailing separator -- or `/sdcard` against `/storage/emulated/0`, both live on Android -- + * is one connector but two strings. Guessing wrong here only costs a needless reconnect. + */ + private fun sameDirectory( + a: String, + b: String, + ): Boolean { + val first = File(a) + val second = File(b) + return first == second || + runCatching { first.canonicalFile == second.canonicalFile }.getOrDefault(false) + } + + /** + * Whether a wrapper connection is still bound to the distribution the wrapper names. + * + * [GradleDistributionParams.WRAPPER] carries no version, so two wrapper params compare equal + * across a wrapper upgrade. The distribution is resolved from `gradle-wrapper.properties` + * inside `connect()` and frozen into the connection, and [Main.checkGradleWrapper] can + * rewrite that file earlier in this same initialize -- so without this the initialize that + * installs a new wrapper is exactly the one that reuses the connection bound to the old one. + */ + @VisibleForTesting + internal fun wrapperStillMatches( + params: InitializeProjectParams, + recorded: String?, + current: String? = wrapperDistributionUrl(params.directory), + ): Boolean = + params.gradleDistribution.type != GradleDistributionType.GRADLE_WRAPPER || + recorded == current + + /** The `distributionUrl` named by [directory]'s Gradle wrapper, or null if unreadable. */ + @VisibleForTesting + internal fun wrapperDistributionUrl(directory: String): String? = + runCatching { + File(directory, WRAPPER_PROPERTIES) + .takeIf(File::isFile) + ?.inputStream() + ?.use { stream -> Properties().apply { load(stream) } } + ?.getProperty("distributionUrl") + }.getOrNull() } + /** + * Whether the connector already open can serve [params] without reconnecting. + * + * Not merely a slow path when false: reconnecting disconnects the open connector, and + * `GradleConnector.disconnect()` sends the running daemon `StopWhenIdle` (ADFA-5589). + */ + @VisibleForTesting + internal fun canReuseConnector(params: InitializeProjectParams): Boolean = + connector != null && + connection != null && + describesSameConnection(lastInitParams, params) && + wrapperStillMatches(params, lastWrapperDistribution) + @VisibleForTesting internal fun getOrConnectProject( projectDir: File, @@ -116,14 +223,31 @@ internal class ToolingApiServerImpl( ?: GradleDistributionParams.WRAPPER, ): Pair = withStopWatch("getOrConnectProject") { - if (!forceConnect && connector != null && connection != null) { - return@withStopWatch connector!! to connection!! + // Each field read once into a local. Four separate reads of two fields could pass the + // null checks and then throw on the !!: the reconnect below nulls both before it + // connects, so unlike before this fix they are null mid-flight on every reconnect, not + // only at shutdown. + val openConnector = connector + val openConnection = connection + if (!forceConnect && openConnector != null && openConnection != null) { + return@withStopWatch openConnector to openConnection } if (forceConnect) { - connector?.disconnect() + // The local, not the field. Re-reading it here is what the locals above exist to + // avoid: a concurrent reconnect can install a new connector between the two reads, + // and this would then disconnect that one and drop the one it meant to close. + openConnector?.disconnect() } + // Dropped before the connect, not after it. A connect that throws -- a bad installation + // directory, an unreachable distribution -- would otherwise leave the disconnected pair in + // place, and the next initialize whose params match would reuse a dead connection and fail + // every build with CONNECTION_CLOSED until the server process restarts. + this.connector = null + this.connection = null + this.lastWrapperDistribution = null + val connector = GradleConnector.newConnector().forProjectDirectory(projectDir) setupConnectorForGradleInstallation(connector, gradleDist) @@ -131,6 +255,12 @@ internal class ToolingApiServerImpl( this.connector = connector this.connection = connection + this.lastWrapperDistribution = + if (gradleDist.type == GradleDistributionType.GRADLE_WRAPPER) { + wrapperDistributionUrl(projectDir.path) + } else { + null + } connector to connection } @@ -141,16 +271,16 @@ internal class ToolingApiServerImpl( } override fun initialize(params: InitializeProjectParams): CompletableFuture { - return runBuild { - val start = System.currentTimeMillis() - try { - return@runBuild doInitialize(params, start) - } catch (err: Throwable) { + val start = System.currentTimeMillis() + return runBuild( + onFailure = { err -> log.error("Failed to initialize project", err) - return@runBuild InitializeResult.Failure( + InitializeResult.Failure( notifyBuildFailure(params.buildId, emptyList(), start, err), ) - } + }, + ) { + doInitialize(params, start) } } @@ -178,8 +308,7 @@ internal class ToolingApiServerImpl( } val stopWatch = StopWatch("Connection to project") - val isReinitializing = - connector != null && connection != null && params == lastInitParams + val isReinitializing = canReuseConnector(params) if (isReinitializing) { log.info("Project is being reinitialized") @@ -272,8 +401,13 @@ internal class ToolingApiServerImpl( override fun isServerInitialized(): CompletableFuture = CompletableFuture.supplyAsync { isInitialized } override fun executeTasks(message: TaskExecutionMessage): CompletableFuture { - return runBuild { - val start = System.currentTimeMillis() + val start = System.currentTimeMillis() + return runBuild( + onFailure = { error -> + log.error("Failed to run tasks: {}", message.tasks, error) + TaskExecutionResult(false, notifyBuildFailure(message.buildId, message.tasks, start, error)) + }, + ) { if (!isServerInitialized().get()) { log.error("Cannot execute tasks: {}", PROJECT_NOT_INITIALIZED) return@runBuild TaskExecutionResult(false, PROJECT_NOT_INITIALIZED) @@ -317,12 +451,6 @@ internal class ToolingApiServerImpl( try { builder.run() - } catch (error: Throwable) { - log.error("Failed to run tasks: {}", message.tasks, error) - return@runBuild TaskExecutionResult( - false, - notifyBuildFailure(message.buildId, message.tasks, start, error), - ) } finally { // On both paths. Only the success path cleared it, so every failed build left a // token behind for a source that was already finished. The next Stop then @@ -340,7 +468,7 @@ internal class ToolingApiServerImpl( durationMs = System.currentTimeMillis() - start, ), ) - return@runBuild TaskExecutionResult.SUCCESS + TaskExecutionResult.SUCCESS } } @@ -537,6 +665,7 @@ internal class ToolingApiServerImpl( this.client = null this.buildCancellationToken = null this.lastInitParams = null + this.lastWrapperDistribution = null // wait for connections to close connectionCloseFuture.get() @@ -545,7 +674,9 @@ internal class ToolingApiServerImpl( null } - private fun getTaskFailureType(error: Throwable): Failure = + /** Classifies [error]. Pure: it reads nothing and changes nothing. */ + @VisibleForTesting + internal fun getTaskFailureType(error: Throwable): Failure = when (error) { is BuildException -> BUILD_FAILED is BuildCancelledException -> BUILD_CANCELLED @@ -562,19 +693,37 @@ internal class ToolingApiServerImpl( action() } - private inline fun runBuild(crossinline action: () -> T): CompletableFuture = + /** + * Runs [action] as the one build in progress, turning anything it throws into [onFailure]'s + * result rather than an exceptionally-completed future. + * + * The catch spans the whole action deliberately. Each caller used to guard only the part that + * talks to Gradle, so everything before it -- resolving a connection, checking the wrapper, + * preparing the build -- escaped as a raw exception, and the client got an ExecutionException + * where it expected a classified failure. That is one bug this file has now had twice, in two + * different statements on the same line, because the fix each time moved the throw instead of + * covering it. + * + * "Build already in progress" is left to throw: it is a caller error rather than a build + * outcome, and it is raised before this takes ownership of the flag. + */ + private inline fun runBuild( + crossinline onFailure: (Throwable) -> T, + crossinline action: () -> T, + ): CompletableFuture = supplyAsync { - if (isBuildInProgress) { + if (!buildInProgress.compareAndSet(false, true)) { log.error("Cannot run build, build is already in progress!") throw IllegalStateException("Build is already in progress") } - isBuildInProgress = true startDaemonWatch() try { action() + } catch (error: Throwable) { + onFailure(error) } finally { - isBuildInProgress = false + buildInProgress.set(false) } } diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImplTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImplTest.kt index 9353bf29e1..42230d04c7 100644 --- a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImplTest.kt +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/ToolingApiServerImplTest.kt @@ -3,7 +3,9 @@ package com.itsaky.androidide.tooling.impl import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.tooling.api.IToolingApiClient import com.itsaky.androidide.tooling.api.messages.BuildId +import com.itsaky.androidide.tooling.api.messages.GradleDistributionParams import com.itsaky.androidide.tooling.api.messages.InitializeProjectParams +import com.itsaky.androidide.tooling.api.messages.TaskExecutionMessage import com.itsaky.androidide.tooling.api.messages.result.BuildCancellationRequestResult import com.itsaky.androidide.tooling.api.messages.result.BuildResult import com.itsaky.androidide.tooling.api.messages.result.InitializeResult @@ -14,19 +16,28 @@ import com.itsaky.androidide.tooling.impl.sync.RootModelBuilder import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject +import io.mockk.mockkStatic import io.mockk.slot import io.mockk.spyk import io.mockk.unmockkAll import io.mockk.verify import org.gradle.tooling.BuildCancelledException +import org.gradle.tooling.BuildLauncher +import org.gradle.tooling.GradleConnectionException import org.gradle.tooling.GradleConnector import org.gradle.tooling.ProjectConnection +import org.gradle.tooling.events.OperationType +import org.gradle.tooling.events.ProgressListener import org.junit.After import org.junit.Assert.fail import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.nio.file.Files +import java.util.concurrent.CompletableFuture import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException @@ -39,11 +50,13 @@ class ToolingApiServerImplTest { private fun testInitParams( directory: String = "/does/not/exist", forceSync: Boolean = false, + gradleDistribution: GradleDistributionParams = GradleDistributionParams.WRAPPER, ) = InitializeProjectParams( // Required since ADFA-2784 added it, and never supplied here: this file has not compiled // on stage since, and no workflow runs :subprojects: tests, so nothing said so. buildId = BuildId.Unknown, directory = directory, + gradleDistribution = gradleDistribution, needsGradleSync = forceSync, ) @@ -68,7 +81,7 @@ class ToolingApiServerImplTest { every { server.getOrConnectProject( projectDir = any(), - forceConnect = true, + forceConnect = any(), initParams = any(), gradleDist = any(), ) @@ -77,6 +90,178 @@ class ToolingApiServerImplTest { return MockServer(server, connector, connection) } + @Test + fun `GIVEN the same project twice THEN the connector can be reused`() { + // Two separately built objects describing the same connection, which is what the client + // sends: every initialize request arrives freshly deserialized from JSON-RPC. The guard used + // to be `params == lastInitParams`, which is reference equality on this type and so answered + // false for exactly this case (ADFA-5589). + val first = testInitParams() + val second = testInitParams() + + assertThat(first).isNotSameInstanceAs(second) + assertThat(ToolingApiServerImpl.describesSameConnection(first, second)).isTrue() + } + + @Test + fun `GIVEN the same directory spelled differently THEN the connector can be reused`() { + // forProjectDirectory takes a File, so a trailing separator is the same connector. + assertThat( + ToolingApiServerImpl.describesSameConnection( + testInitParams(directory = "/does/not/exist"), + testInitParams(directory = "/does/not/exist/"), + ), + ).isTrue() + } + + @Test + fun `GIVEN a different project directory THEN the connector cannot be reused`() { + // A connector is bound to its project directory, so reusing one across projects would run + // the next build against the previous project's connection. + assertThat( + ToolingApiServerImpl.describesSameConnection( + testInitParams(directory = "/does/not/exist"), + testInitParams(directory = "/somewhere/else"), + ), + ).isFalse() + } + + @Test + fun `GIVEN a different Gradle distribution THEN the connector cannot be reused`() { + // The other thing a connector is bound to. forInstallationDir is what the app actually sends + // for the gradleInstallationDir preference, so that is the case worth pinning: reusing a + // connector here would silently build with the distribution the user just changed away from. + val wrapper = testInitParams() + val installation = + testInitParams(gradleDistribution = GradleDistributionParams.forInstallationDir("/opt/gradle")) + + assertThat(ToolingApiServerImpl.describesSameConnection(wrapper, installation)).isFalse() + } + + @Test + fun `GIVEN nothing initialized yet THEN the connector cannot be reused`() { + assertThat(ToolingApiServerImpl.describesSameConnection(null, testInitParams())).isFalse() + } + + @Test + fun `GIVEN the wrapper names a new distribution THEN the connector cannot be reused`() { + // Two WRAPPER params compare equal across a wrapper upgrade: the distribution is resolved + // from gradle-wrapper.properties inside connect() and frozen into the connection, so reusing + // it would keep building with the Gradle the user just upgraded away from. + assertThat( + ToolingApiServerImpl.wrapperStillMatches( + testInitParams(), + recorded = "https://example.invalid/gradle-8.14.3-bin.zip", + current = "https://example.invalid/gradle-9.0-bin.zip", + ), + ).isFalse() + } + + @Test + fun `GIVEN the wrapper is unchanged THEN the connector can be reused`() { + val url = "https://example.invalid/gradle-8.14.3-bin.zip" + assertThat( + ToolingApiServerImpl.wrapperStillMatches(testInitParams(), recorded = url, current = url), + ).isTrue() + } + + @Test + fun `GIVEN a non-wrapper distribution THEN the wrapper properties do not matter`() { + // An installation-dir connection does not read gradle-wrapper.properties at all. + assertThat( + ToolingApiServerImpl.wrapperStillMatches( + testInitParams(gradleDistribution = GradleDistributionParams.forInstallationDir("/opt/gradle")), + recorded = null, + current = "https://example.invalid/gradle-9.0-bin.zip", + ), + ).isTrue() + } + + @Test + fun `GIVEN a wrapper properties file THEN its distribution URL is read`() { + val project = Files.createTempDirectory("adfa5589").toFile() + val properties = File(project, "gradle/wrapper/gradle-wrapper.properties") + properties.parentFile.mkdirs() + properties.writeText("distributionUrl=https\\://example.invalid/gradle-8.14.3-bin.zip\n") + + assertThat(ToolingApiServerImpl.wrapperDistributionUrl(project.path)) + .isEqualTo("https://example.invalid/gradle-8.14.3-bin.zip") + assertThat(ToolingApiServerImpl.wrapperDistributionUrl("/does/not/exist")).isNull() + + project.deleteRecursively() + } + + @Test + fun `GIVEN the connector can be reused WHEN initializing THEN do not force a reconnect`() { + val (server) = mockkReusableServer(canReuse = true) + + server.initialize(testInitParams()).get(5, TimeUnit.SECONDS) + + // forceConnect is the whole point of the reuse check: it is what reaches + // connector.disconnect(), and that is what sends the running daemon StopWhenIdle. Asserting + // describesSameConnection alone would leave this wiring free to invert unnoticed. + verify(exactly = 1) { + server.getOrConnectProject( + projectDir = any(), + forceConnect = false, + initParams = any(), + gradleDist = any(), + ) + } + } + + @Test + fun `GIVEN the connector cannot be reused WHEN initializing THEN force a reconnect`() { + val (server) = mockkReusableServer(canReuse = false) + + server.initialize(testInitParams()).get(5, TimeUnit.SECONDS) + + verify(exactly = 1) { + server.getOrConnectProject( + projectDir = any(), + forceConnect = true, + initParams = any(), + gradleDist = any(), + ) + } + } + + @Test + fun `GIVEN a connect that fails THEN the dead connection is not left behind for reuse`() { + val server = ToolingApiServerImpl() + val connector = mockk(relaxed = true) + every { connector.forProjectDirectory(any()) } returns connector + every { connector.connect() } returns + mockk(relaxed = true) andThenThrows RuntimeException("connect failed") + + mockkStatic(GradleConnector::class) + every { GradleConnector.newConnector() } returns connector + + server.getOrConnectProject(File("/does/not/exist"), forceConnect = true) + assertThat(server.isConnected).isTrue() + + // The reconnect disconnects the open connector before it opens the new one, so a connect + // that throws must not leave that dead pair in place: the next initialize whose params match + // would reuse it and fail every build with CONNECTION_CLOSED until the server restarts. + val reconnect = runCatching { server.getOrConnectProject(File("/does/not/exist"), forceConnect = true) } + + assertThat(reconnect.isFailure).isTrue() + assertThat(server.isConnected).isFalse() + } + + /** A server whose connect, project directory check and Gradle sync are all stubbed out. */ + private fun mockkReusableServer(canReuse: Boolean): MockServer { + mockkObject(RootModelBuilder) + every { + RootModelBuilder.build(any(), any()) + } returns ProjectSyncHelper.cacheFileForProject(File("/does/not/exist")) + + val mocks = mockkToolingServer() + every { mocks.server.validateProjectDirectory(any()) } returns null + every { mocks.server.canReuseConnector(any()) } returns canReuse + return mocks + } + @Test fun `GIVEN any initialization params WHEN project init fails THEN report as failure`() { mockkObject(RootModelBuilder) @@ -217,6 +402,104 @@ class ToolingApiServerImplTest { } } + @Test + fun `GIVEN the build throws a GradleConnectionException THEN the connection is kept and not disconnected`() { + // A ProjectConnection is stopped only by our own close() or disconnect(). It does not die + // with the daemon, so the next run() on it starts a fresh one. Reconnecting after a failed + // build would disconnect() -- which sends the running daemon StopWhenIdle -- and cost the + // cold start ADFA-5589 exists to prevent. + val server = spyk(ToolingApiServerImpl()) + val connector = mockk(relaxed = true) + val connection = mockk(relaxed = true) + val builder = mockk(relaxed = true) + every { connector.forProjectDirectory(any()) } returns connector + every { connector.connect() } returns connection + every { connection.newBuild() } returns builder + // A relaxed mock cannot return itself from these generic, self-typed setters. + every { builder.setStandardInput(any()) } returns builder + every { builder.setStandardOutput(any()) } returns builder + every { builder.setStandardError(any()) } returns builder + every { builder.addProgressListener(any(), any>()) } returns builder + every { builder.addArguments(any>()) } returns builder + every { builder.addJvmArguments(any>()) } returns builder + every { builder.withCancellationToken(any()) } returns builder + every { builder.run() } throws GradleConnectionException("daemon disappeared", RuntimeException()) + + mockkStatic(GradleConnector::class) + every { GradleConnector.newConnector() } returns connector + + mockkObject(Main) + every { Main.checkGradleWrapper() } returns Unit + every { server.isServerInitialized() } returns CompletableFuture.completedFuture(true) + + server.getOrConnectProject(File("/does/not/exist"), forceConnect = true) + + val message = TaskExecutionMessage(tasks = listOf("assembleDebug"), buildId = BuildId.Unknown) + repeat(2) { + val result = server.executeTasks(message).get(5, TimeUnit.SECONDS) + assertThat(result.isSuccessful).isFalse() + assertThat(result.failure).isEqualTo(TaskExecutionResult.Failure.CONNECTION_ERROR) + } + + assertThat(server.isConnected).isTrue() + // Both builds ran on the one connection, which was opened once. + verify(exactly = 1) { connector.connect() } + verify(exactly = 2) { connection.newBuild() } + verify(exactly = 0) { connector.disconnect() } + verify(exactly = 0) { connection.close() } + } + + @Test + fun `GIVEN no open connection THEN the build reports a failure rather than completing exceptionally`() { + // mockkToolingServer stubs getOrConnectProject, so nothing was connected. + val (server) = mockkToolingServer() + every { server.isServerInitialized() } returns CompletableFuture.completedFuture(true) + + mockkObject(Main) + every { Main.checkGradleWrapper() } returns Unit + + // Everything before the Gradle call used to sit outside the try, so a throw here escaped as + // an ExecutionException where the client expected a classified failure. + val result = + server + .executeTasks(TaskExecutionMessage(tasks = listOf("assembleDebug"), buildId = BuildId.Unknown)) + .get(5, TimeUnit.SECONDS) + + assertThat(result.isSuccessful).isFalse() + assertThat(result.failure).isEqualTo(TaskExecutionResult.Failure.CONNECTION_CLOSED) + } + + @Test + fun `GIVEN a build already running THEN a second is refused rather than sharing its connection`() { + // The refusal, not the atomicity. This passes against a read-then-write too -- the first + // build has set the flag long before the second reads it -- so it pins the behaviour and + // not the CAS. A genuine interleaving is not reproducible on demand, so the compareAndSet + // in runBuild is argued from the threading model rather than pinned here. + val (server) = mockkToolingServer() + every { server.isServerInitialized() } returns CompletableFuture.completedFuture(true) + + val started = java.util.concurrent.CountDownLatch(1) + val release = java.util.concurrent.CountDownLatch(1) + mockkObject(Main) + every { Main.checkGradleWrapper() } answers { + started.countDown() + release.await(5, TimeUnit.SECONDS) + throw IllegalStateException("done") + } + + val first = server.executeTasks(TaskExecutionMessage(tasks = listOf("a"), buildId = BuildId.Unknown)) + assertThat(started.await(5, TimeUnit.SECONDS)).isTrue() + + val second = server.executeTasks(TaskExecutionMessage(tasks = listOf("b"), buildId = BuildId.Unknown)) + val refused = runCatching { second.get(5, TimeUnit.SECONDS) }.exceptionOrNull() + + release.countDown() + first.get(5, TimeUnit.SECONDS) + + assertThat(refused).isNotNull() + assertThat(refused).hasCauseThat().hasMessageThat().contains("already in progress") + } + @Test fun `GIVEN readable sync files WHEN the stored schema version is stale THEN sync anyway`() { val initParams = testInitParams(forceSync = false)