diff --git a/subprojects/project-models/src/main/proto/android.proto b/subprojects/project-models/src/main/proto/android.proto index 8f3e9f2600..f2d2afd701 100644 --- a/subprojects/project-models/src/main/proto/android.proto +++ b/subprojects/project-models/src/main/proto/android.proto @@ -19,26 +19,64 @@ enum ProjectType { * A node in a dependency graph, representing a direct or transitive dependency. * * This does not directly contain artifact information, instead it focuses on the graph - * information (transitive dependencies) as well as the usage of this particular dependency - * in this node of the graph (ie what are its modifiers: what version was originally requested.) + * information (transitive dependencies). * + * Nodes are deduplicated by key, so there is one node per resolved artifact rather than one per + * usage. Per-usage detail is therefore no longer representable: see [requestedCoordinatesId]. */ -message GraphItem { +message GraphNode { /** - * A Unique key representing the library, and allowing to match it with a [Library] instance + * Index into [DependencyGraph.key] of this node's unique library key, which matches it with a + * [Library] instance. */ - string key = 1; + uint32 keyId = 1; /** - * Returns this library's Maven coordinates, as requested in the build file. + * Index into [DependencyGraph.requestedCoordinates] of the Maven coordinates this library was + * requested with in the build file. + * + * Requested coordinates are a property of a usage, not of the resolved artifact, so where several + * dependents request the same artifact at different coordinates this records only the occurrence + * the flattening reached first. + * + * Check presence before reading: unset reads back as 0, which is also a valid index into + * [DependencyGraph.requestedCoordinates]. */ - optional string requestedCoordinates = 2; + optional uint32 requestedCoordinatesId = 2; /** - * Return the direct dependency of this node. + * Indices into [DependencyGraph.node] of this node's direct dependencies. */ - repeated GraphItem dependency = 3; + repeated uint32 dependency = 3; +} + +/** + * A dependency graph, stored flat. + * + * The previous representation nested each node's children inline, so a dependency DAG serialised as + * a tree and every path to a shared artifact duplicated that artifact's entire subtree. Measured on + * an 86-module project that produced 786,554 nodes holding 1,011,910 key strings for 57,517 distinct + * values -- a 17.6x duplication, with one kotlin-stdlib key repeated 180,738 times. + * + * Nodes are deduplicated by key and strings interned, so each artifact and each string appears once. + * The compile-classpath consumer already expands each key at most once via a visited set, over the + * same pre-order walk, so it sees the same graph. The module-dependency consumer reads only the + * roots, whose order and multiplicity are unchanged. + */ +message DependencyGraph { + + /** Interned node keys, indexed by [GraphNode.keyId]. */ + repeated string key = 1; + + /** Interned requested coordinates, indexed by [GraphNode.requestedCoordinatesId]. */ + repeated string requestedCoordinates = 2; + + /** Every distinct node, deduplicated by key. */ + repeated GraphNode node = 3; + + /** Indices into [node] of the graph's direct dependencies. */ + repeated uint32 root = 4; } // An unresolved dependency. @@ -53,15 +91,18 @@ message UnresolvedDependency { // The dependencies information for a given artifact. // -// It contains the compile graph, always, and optionally the runtime graph. +// It contains the compile graph. The runtime graph is omitted for now. // -// Each graph is fairly lightweight, with each artifact node being mostly an address, children, -// and modifiers that are specific to this particular usage of the artifact rather than -// artifact properties. +// The graph is stored flat: nodes are deduplicated by key and strings interned, so each artifact +// appears once and carries an address plus its children. Per-usage modifiers do not survive that +// deduplication -- see GraphNode. message ArtifactDependencies { - // The compile dependency graph. - repeated GraphItem compileDependency = 1; + // The compile dependency graph, stored flat. See DependencyGraph. + DependencyGraph compileGraph = 3; + + reserved 1; + reserved "compileDependency"; // NOTE: We omit runtime dependencies for now. diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt index 5e1e483ad2..005ba2b253 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt @@ -152,6 +152,9 @@ open class AndroidModule( return emptySet() } + // After the guard: a cyclic re-entry must not clear the flag while the outer walk is running. + reportedGraphDamage = false + val result = mutableSetOf() if (excludeSourceGeneratedClassPath) { // TODO: The mainArtifact.classJars are technically generated from source files @@ -163,9 +166,11 @@ open class AndroidModule( } else { result.addAll(getModuleClasspaths()) } + val graph = variantDependencies.mainArtifact.compileGraph collectLibraries( root = project, - libraries = variantDependencies.mainArtifact?.compileDependencyList ?: emptyList(), + graph = graph, + nodeIds = graph.rootList, result = result, excludeSourceGeneratedClassPath = excludeSourceGeneratedClassPath, visited = HashSet(), @@ -251,11 +256,46 @@ open class AndroidModule( } /** - * Recursively collect the compile classpath entries contributed by the given dependency-graph - * [libraries] into [result], guarding against cycles. + * Whether the current traversal has already reported a damaged dependency-graph index. + * + * Deliberately unsynchronised: two concurrent classpath computations can cost an extra log line + * or swallow one, neither of which is worth a lock on this path. + */ + @Volatile + private var reportedGraphDamage = false + + /** + * Report the first out-of-range graph index seen in the current traversal. + * + * A truncated node table makes every index dangle, so warning per index would put tens of + * thousands of lines in the log on every classpath refresh. One line per traversal says the + * same thing. + */ + private fun logLostGraphEntry( + nodeId: Int, + keyId: Int?, + ) { + if (reportedGraphDamage) { + return + } + + reportedGraphDamage = true + val entry = if (keyId == null) "node index $nodeId" else "key index $keyId of node $nodeId" + log.warn( + "Dependency graph {} in module {} is out of range; the project cache looks damaged." + + " Re-sync the project if symbols fail to resolve.", + entry, + path, + ) + } + + /** + * Recursively collect the compile classpath entries contributed by the [graph] nodes at + * [nodeIds] into [result], guarding against cycles. * * @param root The workspace used to resolve project dependencies by path. - * @param libraries The dependency-graph nodes to expand at this level. + * @param graph The flat dependency graph the node indices address. + * @param nodeIds Indices into [graph] of the nodes to expand at this level. * @param result The accumulating set of classpath files. * @param excludeSourceGeneratedClassPath Whether to exclude source-generated classpath entries. * @param visited Keys of dependency-graph nodes already expanded within this module; each node is @@ -265,20 +305,34 @@ open class AndroidModule( */ private fun collectLibraries( root: Workspace, - libraries: List, + graph: AndroidModels.DependencyGraph, + nodeIds: List, result: MutableSet, excludeSourceGeneratedClassPath: Boolean, visited: MutableSet, moduleVisited: MutableSet, ) { val libraryMap = variantDependencies.librariesMap - for (library in libraries) { + for (nodeId in nodeIds) { + /* + * Indices come off disk. The nested form carried each key inline, so a damaged cache + * cost a classpath entry; addressing by index would turn the same damage into an + * IndexOutOfBoundsException out of a classpath getter, so skip instead. A silently + * short classpath reads as phantom unresolved symbols, so say so in the log. + */ + val node = graph.nodeList.getOrNull(nodeId) + val key = node?.let { graph.keyList.getOrNull(it.keyId) } + if (key == null) { + logLostGraphEntry(nodeId, node?.keyId) + continue + } + // Guard against cyclic dependency graphs within this module: expand each graph node once. - if (!visited.add(library.key)) { + if (!visited.add(key)) { continue } - val lib = libraryMap[library.key] ?: continue + val lib = libraryMap[key] ?: continue when { lib.type == AndroidModels.LibraryType.Project -> { val module = root.findByPath(lib.projectInfo!!.projectPath) ?: continue @@ -301,7 +355,8 @@ open class AndroidModule( collectLibraries( root = root, - libraries = library.dependencyList, + graph = graph, + nodeIds = node.dependencyList, result = result, excludeSourceGeneratedClassPath = excludeSourceGeneratedClassPath, visited = visited, @@ -328,14 +383,24 @@ open class AndroidModule( return emptyList() } + // After the guard: a cyclic re-entry must not clear the flag while the outer walk is running. + reportedGraphDamage = false + recursionPath.addLast(path) try { val result = mutableListOf() - val libraries = variantDependencies.mainArtifact.compileDependencyList + val graph = variantDependencies.mainArtifact.compileGraph val libraryMap = variantDependencies.librariesMap - for (library in libraries) { - val lib = libraryMap[library.key] ?: continue + for (nodeId in graph.rootList) { + val node = graph.nodeList.getOrNull(nodeId) + val key = node?.let { graph.keyList.getOrNull(it.keyId) } + if (key == null) { + logLostGraphEntry(nodeId, node?.keyId) + continue + } + + val lib = libraryMap[key] ?: continue if (lib.type != AndroidModels.LibraryType.Project) { continue } diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt index e6416e53ca..d115016047 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt @@ -53,7 +53,8 @@ class CompileModuleProjectsCycleTest { /** * Build a real [AndroidModule] at Gradle [path] whose compile-scope project dependencies are * [moduleDeps] (Gradle project paths). The dependency graph is encoded exactly the way the tooling - * layer encodes it: a [AndroidModels.GraphItem] in the main artifact's compile graph keyed to a + * layer encodes it: a [AndroidModels.GraphNode] in the main artifact's [AndroidModels.DependencyGraph], + * listed as a root and keyed - through the graph's interned key table - to a * [AndroidModels.Library] of type [AndroidModels.LibraryType.Project] that points at the dependency * module via [AndroidModels.ProjectInfo.getProjectPath]. */ @@ -61,15 +62,18 @@ class CompileModuleProjectsCycleTest { path: String, moduleDeps: List, ): AndroidModule { - val mainArtifact = AndroidModels.ArtifactDependencies.newBuilder() + val graph = AndroidModels.DependencyGraph.newBuilder() val variantDeps = AndroidModels.VariantDependencies.newBuilder().setName("debug") for (depPath in moduleDeps) { val key = "project$depPath" - mainArtifact.addCompileDependency( - AndroidModels.GraphItem + val keyId = graph.keyCount + graph.addKey(key) + graph.addRoot(graph.nodeCount) + graph.addNode( + AndroidModels.GraphNode .newBuilder() - .setKey(key) + .setKeyId(keyId) .build(), ) variantDeps.putLibraries( @@ -87,7 +91,12 @@ class CompileModuleProjectsCycleTest { ).build(), ) } - variantDeps.setMainArtifact(mainArtifact.build()) + variantDeps.setMainArtifact( + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph.build()) + .build(), + ) val androidProject = AndroidModels.AndroidProject @@ -110,6 +119,134 @@ class CompileModuleProjectsCycleTest { return AndroidModule(gradleProject) } + /** + * A module whose compile graph is `rootLib -> transitiveLib`, both external Java libraries. + * + * The transitive jar is reachable only by following a node's + * [AndroidModels.GraphNode.getDependencyList] and resolving those indices against the graph, so + * it covers the recursive half of the consumer that a flat root list never reaches. + */ + private fun moduleWithTransitiveLibrary( + path: String, + rootJar: String, + transitiveJar: String, + ): AndroidModule { + val graph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey("rootLib") + .addKey("transitiveLib") + .addNode( + AndroidModels.GraphNode + .newBuilder() + .setKeyId(0) + .addDependency(1) + .build(), + ).addNode( + AndroidModels.GraphNode + .newBuilder() + .setKeyId(1) + .build(), + ).addRoot(0) + + val variantDeps = + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putLibraries("rootLib", externalJavaLibrary("rootLib", rootJar)) + .putLibraries("transitiveLib", externalJavaLibrary("transitiveLib", transitiveJar)) + .setMainArtifact( + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph.build()) + .build(), + ) + + val androidProject = + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .setVariantDependencies(variantDeps.build()) + .build() + + return AndroidModule( + GradleModels.GradleProject + .newBuilder() + .setName(path.trimStart(':')) + .setPath(path) + .setProjectDirPath("/tmp/cycle-test${path.replace(':', '/')}") + .setBuildDirPath("/tmp/cycle-test${path.replace(':', '/')}/build") + .setBuildScriptPath("/tmp/cycle-test${path.replace(':', '/')}/build.gradle") + .setAndroidProject(androidProject) + .build(), + ) + } + + /** + * A module whose compile graph carries a dangling root index, a dangling dependency index and a + * node whose key index is out of range, as a `project.pb` damaged on disk would. + */ + private fun moduleWithDanglingGraphIndices(path: String): AndroidModule { + val graph = + AndroidModels.DependencyGraph + .newBuilder() + .addKey("rootLib") + .addNode( + AndroidModels.GraphNode + .newBuilder() + .setKeyId(0) + .addDependency(9) + .build(), + ).addNode( + AndroidModels.GraphNode + .newBuilder() + .setKeyId(4) + .build(), + ).addRoot(0) + .addRoot(1) + .addRoot(7) + + val variantDeps = + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putLibraries("rootLib", externalJavaLibrary("rootLib", "/tmp/root.jar")) + .setMainArtifact( + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph.build()) + .build(), + ) + + return AndroidModule( + GradleModels.GradleProject + .newBuilder() + .setName(path.trimStart(':')) + .setPath(path) + .setProjectDirPath("/tmp/cycle-test${path.replace(':', '/')}") + .setBuildDirPath("/tmp/cycle-test${path.replace(':', '/')}/build") + .setBuildScriptPath("/tmp/cycle-test${path.replace(':', '/')}/build.gradle") + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + .setVariantDependencies(variantDeps.build()) + .build(), + ).build(), + ) + } + + private fun externalJavaLibrary( + key: String, + artifactPath: String, + ): AndroidModels.Library = + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath(artifactPath) + .build() + /** Install a real [Workspace] containing the given [modules] on the production [ProjectManagerImpl]. */ private fun installWorkspace(vararg modules: ModuleProject) { val root = @@ -139,6 +276,29 @@ class CompileModuleProjectsCycleTest { assertThat(result.map { it.path }).containsExactly(":b", ":a") } + /** A transitive graph node is reached by resolving its index against the flat graph. */ + @Test(timeout = 30_000) + fun `collects a library reachable only through a transitive graph node`() { + val a = moduleWithTransitiveLibrary(":a", "/tmp/root.jar", "/tmp/transitive.jar") + installWorkspace(a) + + val classpaths = a.getCompileClasspaths(excludeSourceGeneratedClassPath = true, visited = HashSet()) + + assertThat(classpaths.map { it.path }).containsAtLeast("/tmp/root.jar", "/tmp/transitive.jar") + } + + /** A damaged cache whose indices dangle costs a classpath entry rather than throwing. */ + @Test(timeout = 30_000) + fun `skips graph indices that are out of range`() { + val a = moduleWithDanglingGraphIndices(":a") + installWorkspace(a) + + val classpaths = a.getCompileClasspaths(excludeSourceGeneratedClassPath = true, visited = HashSet()) + + assertThat(classpaths.map { it.path }).containsExactly("/tmp/root.jar") + assertThat(a.getCompileModuleProjects()).isEmpty() + } + /** A self-dependency (`:a -> :a`) terminates and reports the module once. */ @Test(timeout = 30_000) fun `terminates on a self dependency cycle`() { 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 f01c5ed395..1943edb4c1 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 @@ -201,7 +201,10 @@ internal class ToolingApiServerImpl( val cacheFile = ProjectSyncHelper.cacheFileForProject(projectDir) val syncMetaFile = ProjectSyncHelper.syncMetaFileForProject(projectDir) - if (params.needsGradleSync || !ProjectSyncHelper.areSyncFilesReadable(projectDir)) { + if (params.needsGradleSync || + !ProjectSyncHelper.areSyncFilesReadable(projectDir) || + !ProjectSyncHelper.isSyncMetaVersionCurrent(syncMetaFile) + ) { val cancellationToken = GradleConnector.newCancellationTokenSource() buildCancellationToken = cancellationToken diff --git a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt index 389bc92309..8c61f79934 100644 --- a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt +++ b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt @@ -27,7 +27,8 @@ import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.project.AndroidProject import com.itsaky.androidide.project.AndroidVariant import com.itsaky.androidide.project.ArtifactDependencies -import com.itsaky.androidide.project.GraphItem +import com.itsaky.androidide.project.DependencyGraph +import com.itsaky.androidide.project.GraphNode import com.itsaky.androidide.project.JavaCompilerSettings import com.itsaky.androidide.project.Library import com.itsaky.androidide.project.LibraryInfo @@ -124,16 +125,80 @@ fun LibraryInfo.asProtoModel() = fun ArtifactDependencies.asProtoModel() = ArtifactDependencies( - compileDependencyList = this.compileDependencies.map { it.asProtoModel() }, + compileGraph = DependencyGraphBuilder().build(this.compileDependencies), unresolvedDependencyList = this.unresolvedDependencies.map { it.asProtoModel() }, ) -fun GraphItem.asProtoModel(): AndroidModels.GraphItem = - GraphItem( - key = this.key, - requestedCoordinates = this.requestedCoordinates, - dependencyList = this.dependencies.map { it.asProtoModel() }, - ) +/** + * Flattens AGP's nested [GraphItem] tree into a [AndroidModels.DependencyGraph]. + * + * AGP hands the dependency graph back as a tree: a node shared by several dependents is repeated + * once per path, and each copy carries its own key string. On an 86-module project that expanded to + * 786,554 nodes and 1,011,910 key strings covering 57,517 distinct values. Deduplicating by key + * keeps the first occurrence of each key and the edges recorded on it. The compile-classpath + * consumer expands each key at most once over the same pre-order walk, so it sees the same graph; + * the module-dependency consumer reads only the roots, whose order and multiplicity are unchanged. + * What a later occurrence carried -- its requested coordinates -- is not represented; see + * [AndroidModels.GraphNode]. + * + * Differing children per occurrence would matter, because the classpath consumer prunes a subtree + * whose key has no Library entry while this builder walks it regardless. AGP does not produce that: + * FullDependencyGraphBuilder.handleDependency memoises on a Map + * and hands back the same instance for every occurrence. The key is derived from that same variant, + * so one key resolves to one instance, and therefore to one child list. + */ +private class DependencyGraphBuilder { + /* + * Node index per key, in insertion order. Nodes are deduplicated by key and each new node + * contributes exactly one key, so a node's index into `nodes` is also its index into the + * emitted key table -- these keys are the key table. + * + * [AndroidModels.GraphNode.getKeyId] is still written, rather than dropped in favour of that + * identity, so the schema stays independent of this builder's ordering. + */ + private val nodeIds = LinkedHashMap() + private val requestedCoordinates = LinkedHashMap() + private val nodes = mutableListOf() + + fun build(roots: Collection): AndroidModels.DependencyGraph { + val rootIds = roots.map(::nodeIdOf) + return DependencyGraph( + keyList = nodeIds.keys.toList(), + requestedCoordinatesList = requestedCoordinates.keys.toList(), + nodeList = nodes.toList(), + rootList = rootIds, + ) + } + + /** + * The index of [item]'s node, adding it and its dependencies if this key is new. + * + * The index is reserved before the children are walked, so a cyclic graph terminates. + */ + private fun nodeIdOf(item: GraphItem): Int { + /* + * Empty requested coordinates are treated as absent: AGP's own default is an empty string, + * and interning it would report the field as present against the proto's presence contract. + */ + nodeIds[item.key]?.let { return it } + + val id = nodes.size + nodeIds[item.key] = id + nodes += AndroidModels.GraphNode.getDefaultInstance() + + val node = + GraphNode( + keyId = id, + requestedCoordinatesId = + item.requestedCoordinates?.takeIf { it.isNotEmpty() }?.let { coordinates -> + requestedCoordinates.getOrPut(coordinates) { requestedCoordinates.size } + }, + dependencyList = item.dependencies.map(::nodeIdOf), + ) + nodes[id] = node + return id + } +} fun UnresolvedDependency.asProtoModel() = UnresolvedDependency( diff --git a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/sync/RootModelBuilder.kt b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/sync/RootModelBuilder.kt index a379515d85..c59294d27a 100644 --- a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/sync/RootModelBuilder.kt +++ b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/sync/RootModelBuilder.kt @@ -181,9 +181,9 @@ object RootModelBuilder : ) runBlocking { - syncMetaFile.outputStream().buffered().use { out -> - ProjectSyncHelper - .createSyncMeta( + ProjectSyncHelper.writeSyncMetaSync( + syncMeta = + ProjectSyncHelper.createSyncMeta( projectDir = projectDir, includeChecksum = true, projectModelInfo = @@ -191,9 +191,9 @@ object RootModelBuilder : projectCacheFile.absolutePath, projectCacheFile.sha256(), ), - ).writeTo(out) - out.flush() - } + ), + targetFile = syncMetaFile, + ) } } diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncLockTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncLockTest.kt new file mode 100644 index 0000000000..7280053fa1 --- /dev/null +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncLockTest.kt @@ -0,0 +1,137 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.tooling.api.sync + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.utils.SharedEnvironment +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import java.io.File +import java.io.FileOutputStream +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.util.concurrent.Executors + +/** + * Tests that the sync lock serialises threads within this process. + * + * @author Akash Yadav + */ +@RunWith(JUnit4::class) +class SyncLockTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @Test + fun `a second thread cannot take the sync lock while it is held`() { + val projectDir = temporaryFolder.newFolder("project") + val channel = ProjectSyncHelper.tryAcquireSyncLock(projectDir, ACQUIRE_TIMEOUT_MS) + assertThat(channel).isNotNull() + + try { + assertThat(acquireOnAnotherThread(projectDir)).isNull() + } finally { + ProjectSyncHelper.releaseSyncLock(channel) + } + } + + @Test + fun `the sync lock is available again once it is released`() { + val projectDir = temporaryFolder.newFolder("project") + ProjectSyncHelper.releaseSyncLock( + ProjectSyncHelper.tryAcquireSyncLock(projectDir, ACQUIRE_TIMEOUT_MS), + ) + + val reacquired = acquireOnAnotherThread(projectDir) + assertThat(reacquired).isNotNull() + ProjectSyncHelper.releaseSyncLock(reacquired) + } + + @Test + fun `a failed channel open does not leak the in-process permit`() { + val projectDir = temporaryFolder.newFolder("project") + ProjectSyncHelper.releaseSyncLock(ProjectSyncHelper.tryAcquireSyncLock(projectDir, ACQUIRE_TIMEOUT_MS)) + + val lockFile = File(projectDir, SharedEnvironment.PROJECT_SYNC_CACHE_LOCK_FILE) + lockFile.setWritable(false) + try { + assumeTrue(runCatching { FileOutputStream(lockFile).use { } }.isFailure) + assertThat(ProjectSyncHelper.tryAcquireSyncLock(projectDir, CONTENDED_TIMEOUT_MS)).isNull() + } finally { + lockFile.setWritable(true) + } + + // A permit held by the failed attempt would make the lock unavailable for this JVM's life. + val reacquired = ProjectSyncHelper.tryAcquireSyncLock(projectDir, ACQUIRE_TIMEOUT_MS) + assertThat(reacquired).isNotNull() + ProjectSyncHelper.releaseSyncLock(reacquired) + } + + /** + * Two spellings of one project directory map to one mutex. + * + * Asserted on the key rather than on `tryAcquireSyncLock`, which returns null either way: with + * two mutexes the second caller opens a second channel and `tryLock` throws, which the catch + * also turns into null. The key is the only in-process signal that tells the two apart. + */ + @Test + fun `an aliased project path maps to the same lock key`() { + val projectDir = temporaryFolder.newFolder("project") + val alias = File(temporaryFolder.root, "alias") + assumeTrue(runCatching { Files.createSymbolicLink(alias.toPath(), projectDir.toPath()) }.isSuccess) + + val lockPathOf = { dir: File -> dir.toPath().resolve(SharedEnvironment.PROJECT_SYNC_CACHE_LOCK_FILE) } + Files.createDirectories(lockPathOf(projectDir).parent) + + assertThat(ProjectSyncHelper.lockKeyOf(lockPathOf(alias))) + .isEqualTo(ProjectSyncHelper.lockKeyOf(lockPathOf(projectDir))) + } + + @Test + fun `a relative project path maps to the same lock key as its absolute form`() { + val projectDir = temporaryFolder.newFolder("project") + val lockPathOf = { dir: File -> dir.toPath().resolve(SharedEnvironment.PROJECT_SYNC_CACHE_LOCK_FILE) } + Files.createDirectories(lockPathOf(projectDir).parent) + + val viaParent = File(projectDir, "..").toPath().resolve(projectDir.name) + + assertThat(ProjectSyncHelper.lockKeyOf(viaParent.resolve(SharedEnvironment.PROJECT_SYNC_CACHE_LOCK_FILE))) + .isEqualTo(ProjectSyncHelper.lockKeyOf(lockPathOf(projectDir))) + } + + private fun acquireOnAnotherThread(projectDir: File): FileChannel? { + val executor = Executors.newSingleThreadExecutor() + try { + return executor + .submit { + ProjectSyncHelper.tryAcquireSyncLock(projectDir, CONTENDED_TIMEOUT_MS) + }.get() + } finally { + executor.shutdownNow() + } + } + + private companion object { + const val ACQUIRE_TIMEOUT_MS = 2_000L + const val CONTENDED_TIMEOUT_MS = 200L + } +} diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncMetaVersionTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncMetaVersionTest.kt new file mode 100644 index 0000000000..799c705e8e --- /dev/null +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/api/sync/SyncMetaVersionTest.kt @@ -0,0 +1,186 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.tooling.api.sync + +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.runBlocking +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import java.io.File + +/** + * Tests that sync files written by an incompatible schema version are discarded and resynced. + * + * @author Akash Yadav + */ +@RunWith(JUnit4::class) +class SyncMetaVersionTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @Test + fun `sync is not needed when the stored meta version is current`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, ProjectSyncHelper.SYNC_META_VERSION) + + assertThat(runBlocking { ProjectSyncHelper.checkSyncNeeded(projectDir) }).isFalse() + assertSyncFilesExist(projectDir) + } + + @Test + fun `sync is needed and the stale files are discarded when the stored meta version differs`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, metaVersion = "0") + + assertThat(runBlocking { ProjectSyncHelper.checkSyncNeeded(projectDir) }).isTrue() + assertSyncFilesDiscarded(projectDir) + } + + @Test + fun `sync is needed and the stale files are discarded when the stored meta is unreadable`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, ProjectSyncHelper.SYNC_META_VERSION) + + // field number 0 is not a valid protobuf tag + ProjectSyncHelper.syncMetaFileForProject(projectDir).writeBytes(byteArrayOf(0, 1, 2, 3)) + + assertThat(runBlocking { ProjectSyncHelper.checkSyncNeeded(projectDir) }).isTrue() + assertSyncFilesDiscarded(projectDir) + } + + @Test + fun `a sync is still requested when the stale sync files cannot be discarded`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, metaVersion = "0") + + // Blocks the lock file from being created, so the discard fails before it deletes anything. + val syncDir = ProjectSyncHelper.syncMetaFileForProject(projectDir).parentFile + syncDir.setWritable(false) + + try { + /* + * Probe rather than trust the chmod's return value: running as root it succeeds and + * writes still go through, which would fail this test for the wrong reason. Inside the + * try, so a skipped run still restores the directory. + */ + assumeTrue(runCatching { File(syncDir, "probe").createNewFile() }.getOrDefault(false).not()) + + assertThat(runBlocking { ProjectSyncHelper.checkSyncNeeded(projectDir) }).isTrue() + assertSyncFilesExist(projectDir) + } finally { + syncDir.setWritable(true) + } + } + + @Test + fun `the stored meta version is current when a sync wrote it`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, ProjectSyncHelper.SYNC_META_VERSION) + + assertThat( + ProjectSyncHelper.isSyncMetaVersionCurrent( + ProjectSyncHelper.syncMetaFileForProject(projectDir), + ), + ).isTrue() + } + + @Test + fun `the stored meta version is not current when an older schema wrote it`() { + val projectDir = seedProject() + seedSyncFiles(projectDir, metaVersion = "0") + + assertThat( + ProjectSyncHelper.isSyncMetaVersionCurrent( + ProjectSyncHelper.syncMetaFileForProject(projectDir), + ), + ).isFalse() + } + + @Test + fun `the stored meta version is not current when the meta cannot be read`() { + val projectDir = seedProject() + + assertThat( + ProjectSyncHelper.isSyncMetaVersionCurrent( + ProjectSyncHelper.syncMetaFileForProject(projectDir), + ), + ).isFalse() + } + + @Test + fun `writing the sync meta replaces a leftover temp file entirely`() { + val projectDir = seedProject() + val metaFile = ProjectSyncHelper.syncMetaFileForProject(projectDir) + metaFile.parentFile.mkdirs() + + // What a sync killed between writing the temp file and publishing it leaves behind. + File(metaFile.path + ".tmp").writeBytes(ByteArray(4096) { 0x7f }) + + val meta = runBlocking { ProjectSyncHelper.createSyncMeta(projectDir, includeChecksum = false) } + ProjectSyncHelper.writeSyncMetaSync(meta, metaFile) + + assertThat(metaFile.readBytes()).isEqualTo(meta.toByteArray()) + } + + private fun seedProject(): File { + val projectDir = temporaryFolder.newFolder("project") + projectDir.resolve("build.gradle").writeText("plugins { id 'java' }") + return projectDir + } + + /** + * Write a sync metadata file carrying [metaVersion], plus a project model cache file beside it, + * the way a completed sync leaves them. + */ + private fun seedSyncFiles( + projectDir: File, + metaVersion: String, + ) { + val metaFile = ProjectSyncHelper.syncMetaFileForProject(projectDir) + val cacheFile = ProjectSyncHelper.cacheFileForProject(projectDir) + metaFile.parentFile.mkdirs() + + cacheFile.writeBytes(byteArrayOf()) + + val meta = + runBlocking { + ProjectSyncHelper.createSyncMeta(projectDir, includeChecksum = true) + }.toBuilder() + .setMetaVersion(metaVersion) + .build() + + metaFile.outputStream().buffered().use { out -> + meta.writeTo(out) + out.flush() + } + } + + private fun assertSyncFilesExist(projectDir: File) { + assertThat(ProjectSyncHelper.syncMetaFileForProject(projectDir).exists()).isTrue() + assertThat(ProjectSyncHelper.cacheFileForProject(projectDir).exists()).isTrue() + } + + private fun assertSyncFilesDiscarded(projectDir: File) { + assertThat(ProjectSyncHelper.syncMetaFileForProject(projectDir).exists()).isFalse() + assertThat(ProjectSyncHelper.cacheFileForProject(projectDir).exists()).isFalse() + } +} 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 4d5a8facf9..9353bf29e1 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 @@ -16,10 +16,12 @@ import io.mockk.mockk import io.mockk.mockkObject 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.GradleConnector import org.gradle.tooling.ProjectConnection +import org.junit.After import org.junit.Assert.fail import org.junit.Test import org.junit.runner.RunWith @@ -51,6 +53,12 @@ class ToolingApiServerImplTest { val connection: ProjectConnection, ) + @After + fun tearDown() { + // These tests mock singletons. Left in place they follow the JVM into the next test class. + unmockkAll() + } + private fun mockkToolingServer(): MockServer { val server = spyk(ToolingApiServerImpl()) val connector = mockk(relaxed = true) @@ -209,6 +217,33 @@ class ToolingApiServerImplTest { } } + @Test + fun `GIVEN readable sync files WHEN the stored schema version is stale THEN sync anyway`() { + val initParams = testInitParams(forceSync = false) + val cacheFile = ProjectSyncHelper.cacheFileForProject(File(initParams.directory)) + + mockkObject(RootModelBuilder) + every { RootModelBuilder.build(any(), any()) } returns cacheFile + + mockkObject(ProjectSyncHelper) + + // The overload the server actually calls, so the stub does not ride on internal delegation. + every { ProjectSyncHelper.areSyncFilesReadable(any()) } returns true + every { ProjectSyncHelper.areSyncFilesReadable(any(), any()) } returns true + + // The cache is present and readable, and only the stored schema version rules it out. + every { ProjectSyncHelper.isSyncMetaVersionCurrent(any()) } returns false + + val (server) = mockkToolingServer() + every { server.validateProjectDirectory(any()) } returns null + + val result = server.initialize(initParams).get(5, TimeUnit.SECONDS) + assertThat(result).isInstanceOf(InitializeResult.Success::class.java) + assertThat((result as InitializeResult.Success).cacheFile).isEqualTo(cacheFile) + + verify(exactly = 1) { RootModelBuilder.build(initParams, any()) } + } + @Test fun `shutting the server down stops the daemon watcher`() { // The defect this PR exists to fix, pinned at the caller. The watcher's own shutdown() was diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/DependencyGraphFlatteningTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/DependencyGraphFlatteningTest.kt new file mode 100644 index 0000000000..69039c3afc --- /dev/null +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/DependencyGraphFlatteningTest.kt @@ -0,0 +1,230 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.tooling.impl.serial + +import com.android.builder.model.v2.ide.ArtifactDependencies +import com.android.builder.model.v2.ide.GraphItem +import com.android.builder.model.v2.ide.UnresolvedDependency +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.project.AndroidModels +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +/** + * Covers the flattening of AGP's nested [GraphItem] tree into the interned, index-addressed + * [AndroidModels.DependencyGraph] that [ArtifactDependencies.asProtoModel] emits. + * + * AGP repeats a shared node once per path through the graph, so the serialized form used to grow + * with the number of *paths* rather than the number of *dependencies* (786,554 nodes and 1,011,910 + * key strings for 57,517 distinct dependencies on an 86-module project). These tests pin the two + * properties that make the flattened form lossless: every distinct key becomes exactly one node, + * and the edges still describe the same graph. + */ +@RunWith(JUnit4::class) +class DependencyGraphFlatteningTest { + private class FakeGraphItem( + override var key: String, + override var requestedCoordinates: String? = null, + override var dependencies: List = emptyList(), + ) : GraphItem + + private class FakeArtifactDependencies( + override val compileDependencies: List, + ) : ArtifactDependencies { + override val runtimeDependencies: List = emptyList() + override val unresolvedDependencies: List = emptyList() + } + + private fun graphOf(vararg roots: GraphItem): AndroidModels.DependencyGraph = + FakeArtifactDependencies(roots.toList()).asProtoModel().compileGraph + + /** The key of [graph]'s node at [index], resolved through the graph's interned key table. */ + private fun keyOf( + graph: AndroidModels.DependencyGraph, + index: Int, + ): String = graph.getKey(graph.getNode(index).keyId) + + /** The keys [graph]'s node at [index] depends on, in declaration order. */ + private fun dependencyKeysOf( + graph: AndroidModels.DependencyGraph, + index: Int, + ): List = graph.getNode(index).dependencyList.map { keyOf(graph, it) } + + /** + * The keys the node named [key] depends on. Node indices follow the depth-first walk order, which + * is an implementation detail, so tests that care about edges address nodes by key instead. + */ + private fun dependencyKeysOf( + graph: AndroidModels.DependencyGraph, + key: String, + ): List = dependencyKeysOf(graph, indexOf(graph, key)) + + /** The index of the node named [key]. */ + private fun indexOf( + graph: AndroidModels.DependencyGraph, + key: String, + ): Int = (0 until graph.nodeCount).single { keyOf(graph, it) == key } + + /** The node named [key]. */ + private fun nodeOf( + graph: AndroidModels.DependencyGraph, + key: String, + ): AndroidModels.GraphNode = graph.getNode(indexOf(graph, key)) + + /** The requested coordinates recorded against the node named [key]. */ + private fun coordinatesOf( + graph: AndroidModels.DependencyGraph, + key: String, + ): String = graph.getRequestedCoordinates(nodeOf(graph, key).requestedCoordinatesId) + + @Test + fun `a node shared by two paths is emitted once and referenced twice`() { + // a -> b -> d, a -> c -> d. AGP emits `d` twice; the flattened graph must emit it once. + val d = FakeGraphItem("d") + val a = + FakeGraphItem( + "a", + dependencies = + listOf( + FakeGraphItem("b", dependencies = listOf(d)), + FakeGraphItem("c", dependencies = listOf(d)), + ), + ) + + val graph = graphOf(a) + + assertThat(graph.nodeCount).isEqualTo(4) + assertThat((0 until graph.nodeCount).map { keyOf(graph, it) }).containsExactly("a", "b", "c", "d") + + val b = graph.getNode(graph.getNode(0).getDependency(0)) + val c = graph.getNode(graph.getNode(0).getDependency(1)) + assertThat(b.getDependency(0)).isEqualTo(c.getDependency(0)) + } + + @Test + fun `each distinct key is interned exactly once`() { + // The same shared node reached from two separate roots must not duplicate its key string. + val shared = FakeGraphItem("shared") + val graph = + graphOf( + FakeGraphItem("a", dependencies = listOf(shared)), + FakeGraphItem("b", dependencies = listOf(shared)), + ) + + assertThat(graph.keyList).containsExactly("a", "shared", "b") + assertThat(graph.keyList).containsNoDuplicates() + } + + @Test + fun `edges are preserved`() { + val graph = + graphOf( + FakeGraphItem( + "a", + dependencies = + listOf( + FakeGraphItem("b", dependencies = listOf(FakeGraphItem("d"))), + FakeGraphItem("c", dependencies = listOf(FakeGraphItem("d"))), + ), + ), + ) + + assertThat(dependencyKeysOf(graph, "a")).containsExactly("b", "c").inOrder() + assertThat(dependencyKeysOf(graph, "b")).containsExactly("d") + assertThat(dependencyKeysOf(graph, "c")).containsExactly("d") + assertThat(dependencyKeysOf(graph, "d")).isEmpty() + } + + @Test + fun `roots are recorded in order`() { + val graph = graphOf(FakeGraphItem("a"), FakeGraphItem("b"), FakeGraphItem("c")) + + assertThat(graph.rootList.map { keyOf(graph, it) }).containsExactly("a", "b", "c").inOrder() + } + + @Test + fun `a root reached as a transitive dependency of an earlier root is not duplicated`() { + // `b` is both a root and a dependency of `a`. It must resolve to the same node either way. + val b = FakeGraphItem("b") + val graph = graphOf(FakeGraphItem("a", dependencies = listOf(b)), b) + + assertThat(graph.nodeCount).isEqualTo(2) + assertThat(graph.rootList).containsExactly(0, 1).inOrder() + assertThat(graph.getNode(0).getDependency(0)).isEqualTo(graph.rootList[1]) + } + + @Test(timeout = 10_000) + fun `a cyclic graph terminates and keeps both edges`() { + // The node index is reserved before its children are walked, so a -> b -> a terminates + // instead of recursing until the stack overflows. + val a = FakeGraphItem("a") + val b = FakeGraphItem("b", dependencies = listOf(a)) + a.dependencies = listOf(b) + + val graph = graphOf(a) + + assertThat(graph.nodeCount).isEqualTo(2) + assertThat(dependencyKeysOf(graph, "a")).containsExactly("b") + assertThat(dependencyKeysOf(graph, "b")).containsExactly("a") + } + + @Test(timeout = 10_000) + fun `a self dependency terminates`() { + val a = FakeGraphItem("a") + a.dependencies = listOf(a) + + val graph = graphOf(a) + + assertThat(graph.nodeCount).isEqualTo(1) + assertThat(dependencyKeysOf(graph, "a")).containsExactly("a") + } + + @Test + fun `requested coordinates are interned and optional`() { + val graph = + graphOf( + FakeGraphItem("a", requestedCoordinates = "g:a:1.0"), + FakeGraphItem("b", requestedCoordinates = "g:a:1.0"), + FakeGraphItem("c", requestedCoordinates = "g:c:2.0"), + FakeGraphItem("d"), + ) + + assertThat(graph.requestedCoordinatesList).containsExactly("g:a:1.0", "g:c:2.0").inOrder() + + // Two distinct values, so an intern table that collapsed everything onto one index fails here. + assertThat(coordinatesOf(graph, "a")).isEqualTo("g:a:1.0") + assertThat(coordinatesOf(graph, "b")).isEqualTo("g:a:1.0") + assertThat(coordinatesOf(graph, "c")).isEqualTo("g:c:2.0") + + assertThat(nodeOf(graph, "b").requestedCoordinatesId) + .isEqualTo(nodeOf(graph, "a").requestedCoordinatesId) + assertThat(nodeOf(graph, "c").requestedCoordinatesId) + .isNotEqualTo(nodeOf(graph, "a").requestedCoordinatesId) + assertThat(nodeOf(graph, "d").hasRequestedCoordinatesId()).isFalse() + } + + @Test + fun `an empty dependency list yields an empty graph`() { + val graph = graphOf() + + assertThat(graph.nodeCount).isEqualTo(0) + assertThat(graph.keyList).isEmpty() + assertThat(graph.rootList).isEmpty() + } +} diff --git a/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt b/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt index d9a3905e68..c515d4c475 100644 --- a/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt +++ b/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt @@ -6,15 +6,20 @@ import com.itsaky.androidide.project.SyncMeta import com.itsaky.androidide.project.SyncMetaModels import com.itsaky.androidide.utils.SharedEnvironment import com.itsaky.androidide.utils.sha256 +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext +import org.jetbrains.annotations.VisibleForTesting import org.slf4j.LoggerFactory import java.io.File import java.io.FileNotFoundException import java.io.IOException +import java.io.OutputStream +import java.nio.channels.Channels import java.nio.channels.FileChannel +import java.nio.channels.OverlappingFileLockException import java.nio.file.FileSystems import java.nio.file.FileVisitResult import java.nio.file.Files @@ -25,8 +30,12 @@ import java.nio.file.SimpleFileVisitor import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.nio.file.attribute.BasicFileAttributes +import java.util.Collections +import java.util.WeakHashMap +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Semaphore +import java.util.concurrent.TimeUnit import kotlin.collections.iterator -import kotlin.io.path.outputStream import kotlin.io.path.pathString /** @@ -35,10 +44,45 @@ import kotlin.io.path.pathString * @author Akash Yadav */ object ProjectSyncHelper { + /** + * Version of the on-disk project sync files. + * + * Bump this whenever a persisted proto schema changes incompatibly. A stored version that + * differs from this one discards the sync files and forces a full sync. The models are + * produced and consumed only by the IDE and hold no user data, so discarding them is safe. + */ + const val SYNC_META_VERSION = "2" + private val logger = LoggerFactory.getLogger(ProjectSyncHelper::class.java) + + /** + * Per-lock-file mutex, keyed by the lock file's absolute path. + * + * Closing any channel on a file releases every lock the JVM holds on that file, so two threads + * must never hold overlapping channels on one sync lock file -- the second one's close would + * silently drop the first one's lock. `FileChannel.tryLock` cannot express that (it throws on a + * same-JVM overlap), so in-process contention is settled here, before a channel is opened. + */ + private val inProcessLocks = ConcurrentHashMap() + + /** + * The in-process mutex held on behalf of each acquired channel, released when it is closed. + * + * Weakly keyed: a caller that drops a channel without releasing it can still have the channel + * collected, which closes the descriptor and frees the file lock. A strong map would pin it for + * the life of the process. The permit is not recovered that way, so callers still go through + * [tryUseSyncLock], which releases in a `finally`. + */ + private val heldLocks: MutableMap = + Collections.synchronizedMap(WeakHashMap()) private val hashDispatcher = Dispatchers.Default.limitedParallelism(Runtime.getRuntime().availableProcessors()) + /** + * How long to wait for the sync lock before giving up on discarding the sync files. + */ + private const val DISCARD_LOCK_TIMEOUT_MS = 1_000L + /** * Path matchers for files that we need to watch. */ @@ -110,26 +154,119 @@ object ProjectSyncHelper { timeoutMs: Long, ): FileChannel? { val lockFile = projectDir.resolve(SharedEnvironment.PROJECT_SYNC_CACHE_LOCK_FILE) - Files.createDirectories(lockFile.parent) - val channel = - FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE) - val start = System.currentTimeMillis() - while (System.currentTimeMillis() - start < timeoutMs) { - val lock = channel.tryLock() - if (lock != null) return channel - Thread.sleep(50) + + try { + Files.createDirectories(lockFile.parent) + } catch (err: IOException) { + // Every other failure here answers null; a read-only volume should not be the exception. + logger.warn("Failed to create the sync lock directory", err) + return null + } + + // One deadline for both waits, so a caller's budget is not spent twice over. + val deadline = System.currentTimeMillis() + timeoutMs + val inProcessLock = inProcessLocks.computeIfAbsent(lockKeyOf(lockFile)) { Semaphore(1) } + + try { + if (!inProcessLock.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) { + return null + } + } catch (err: InterruptedException) { + Thread.currentThread().interrupt() + return null + } + + /* + * Held until the channel is handed to the caller, who gives it back through + * releaseSyncLock. Every other exit -- including one thrown before the channel exists -- + * must return the permit, or the sync lock stays unavailable for the life of the process. + */ + var releasePermit = true + + /* + * Closing a channel drops every fcntl lock this process holds on the file, not just this + * channel's. On the one path where another holder may exist -- an overlap the mutex failed + * to prevent -- the descriptor is leaked instead, because taking their lock away is worse + * than an fd. + */ + var closeChannel = true + var channel: FileChannel? = null + try { + channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE) + + /* + * At least one attempt always runs. A semaphore wait that consumed the whole budget + * means the previous holder just handed the lock over, so giving up without trying + * would throw away a sync that was about to succeed. + */ + while (true) { + if (channel.tryLock() != null) { + heldLocks[channel] = inProcessLock + releasePermit = false + return channel + } + + if (System.currentTimeMillis() >= deadline) { + return null + } + + Thread.sleep(50) + } + } catch (err: InterruptedException) { + Thread.currentThread().interrupt() + return null + } catch (err: OverlappingFileLockException) { + // The semaphore above should have made this unreachable; report it rather than spin. + closeChannel = false + logger.warn("Sync lock is already held by this process", err) + return null + } catch (err: IOException) { + logger.warn("Failed to acquire the sync lock", err) + return null + } finally { + if (releasePermit) { + if (closeChannel) { + channel?.close() + } + inProcessLock.release() + } } + } - // Locking failed - channel.close() - return null + /** + * The key a lock file's in-process mutex is stored under. + * + * Resolved through the parent's real path, so two spellings of one directory -- a symlink, a + * relative path, a `..` component -- cannot each get their own mutex and open a second channel + * on the same file. The parent exists by the time this runs; the lock file may not. + * + * Exposed so a test can assert that two spellings agree, which is the whole point of resolving + * the path and is not observable from [tryAcquireSyncLock]'s return value. + */ + @VisibleForTesting + fun lockKeyOf(lockFile: Path): String { + val parent = lockFile.parent ?: return lockFile.toAbsolutePath().normalize().pathString + val realParent = + try { + parent.toRealPath() + } catch (err: IOException) { + logger.debug("Falling back to the normalised sync lock path for {}", parent, err) + parent.toAbsolutePath().normalize() + } + + return realParent.resolve(lockFile.fileName).pathString } /** * Release the sync lock. */ fun releaseSyncLock(channel: FileChannel?) { - channel?.close() + channel ?: return + try { + channel.close() + } finally { + heldLocks.remove(channel)?.release() + } } /** @@ -191,30 +328,80 @@ object ProjectSyncHelper { fun writeGradleBuildSync( gradleBuild: GradleModels.GradleBuild, targetFile: File, + ) = writeAtomically(targetFile) { out -> gradleBuild.writeTo(out) } + + /** + * Write the sync metadata synchronously. + * + * Atomic like the cache beside it: a reader that catches a truncated metadata file sees an + * empty [SyncMetaModels.SyncMeta], whose blank version reads as a schema mismatch. + * + * @param syncMeta The sync metadata model. + * @param targetFile The target file. + */ + fun writeSyncMetaSync( + syncMeta: SyncMetaModels.SyncMeta, + targetFile: File, + ) = writeAtomically(targetFile) { out -> syncMeta.writeTo(out) } + + private fun writeAtomically( + targetFile: File, + write: (OutputStream) -> Unit, ) { // use a temporary file on the same path to allow atomic moves // /data/data and /sdcard are different devices (partitions) // atomic moves are not possible for cross-device moves - val tempCacheFile = Paths.get(targetFile.path + ".tmp") + val tempFile = Paths.get(targetFile.path + ".tmp") runCatching { - tempCacheFile - .outputStream(StandardOpenOption.CREATE, StandardOpenOption.WRITE) - .buffered() - .use { tempOut -> - gradleBuild.writeTo(tempOut) + FileChannel + .open( + tempFile, + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + /* + * A temp file left behind by a killed sync is otherwise written in place, and + * a shorter model publishes with the previous one's tail still attached. + */ + StandardOpenOption.TRUNCATE_EXISTING, + ).use { channel -> + val tempOut = Channels.newOutputStream(channel).buffered() + write(tempOut) tempOut.flush() + /* + * flush() only drains the JVM buffer. Without forcing the data to disk, a + * power loss after the rename can leave a truncated model that still parses. + */ + channel.force(true) } - }.map { + }.mapCatching { // update atomically Files.move( - tempCacheFile, + tempFile, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE, ) + forceDirectory(targetFile.toPath().parent) + }.onFailure { + /* + * A cross-device move fails outright, and the temp file it leaves is what the next + * write would have to overwrite. Truncation covers that case; clearing it here keeps + * a failed write from leaving a stale model on disk at all. + */ + runCatching { Files.deleteIfExists(tempFile) } }.getOrThrow() } + /* + * Persists the rename itself. Best effort: the move has already succeeded, and failing the + * write here would report a model as unpublished while it is in place. + */ + private fun forceDirectory(directory: Path) { + runCatching { + FileChannel.open(directory, StandardOpenOption.READ).use { it.force(true) } + }.onFailure { logger.warn("Unable to sync directory {}", directory, it) } + } + /** * Check whether the project sync files for the given project directory * exist and are readable. @@ -245,9 +432,53 @@ object ProjectSyncHelper { projectCacheFile.exists() && projectCacheFile.canRead() + /** + * Check whether the sync metadata at [syncMetaFile] was written by the current + * [SYNC_META_VERSION]. + * + * Metadata written by an older schema still parses -- a removed field reads back as its default + * rather than failing -- so the project cache beside it can only be trusted once the stored + * version has been checked. Callers that reach the cache without going through + * [checkSyncNeeded] must gate on this. + * + * Blocking: reads and parses the file on the calling thread. Never call it from the main + * thread. + * + * @param syncMetaFile The sync metadata file. + * @return `true` if the stored version is current, `false` if it differs or cannot be read. + */ + fun isSyncMetaVersionCurrent(syncMetaFile: File): Boolean = + try { + readSyncMeta(syncMetaFile).metaVersion == SYNC_META_VERSION + } catch (err: CancellationException) { + throw err + } catch (err: Throwable) { + /* + * A corrupt file normally surfaces as an InvalidProtocolBufferException, but the catch + * is deliberately total: this runs inside checkSyncNeeded's own failure handling, whose + * callers rethrow anything but FileNotFoundException, so an escape here crashes the + * project open instead of resyncing it. A parse that OOMs on a bogus length prefix is + * exactly the case a resync recovers from. + */ + logger.warn("Failed to read sync metadata file: {}", syncMetaFile, err) + false + } + /** * Check if a sync is needed for the given project directory. * + * Not a pure query: once the metadata has been read, files it shows to be unusable -- corrupt, + * or written by a schema version other than [SYNC_META_VERSION] -- are deleted, because they + * would otherwise parse into a silently empty model. The same discard runs when the metadata + * turns out to be unparseable, which leaves a cache nothing can vouch for. It does not run on + * the early return taken when either file is already missing or unreadable. Deletion failures + * are logged, never thrown. + * + * Because it deletes, a re-initialisation that hits the discard can pull the cache out from + * under a read another coroutine already started, which surfaces as a cache read error. That + * needs a version mismatch or corrupt metadata concurrent with an in-flight read, so in + * practice it is the one-time window after a schema bump. + * * @param projectDir The project directory. * @return `true` if a sync is needed, `false` otherwise. */ @@ -269,19 +500,41 @@ object ProjectSyncHelper { return true } - val draft = createSyncMeta(projectDir, includeChecksum = false) val stored = try { loadSyncMetaFromFile(syncMetaFile) } catch (_: FileNotFoundException) { // sync meta is not available, require sync logger.debug("NEED_SYNC: sync meta file not found") + discardSyncFiles(projectDir) return true + } catch (err: CancellationException) { + throw err } catch (err: Throwable) { logger.warn("NEED_SYNC: failed to read sync metadata file", err) + discardSyncFiles(projectDir) return true } + if (stored.metaVersion != SYNC_META_VERSION) { + /* + * The cache file is written before the metadata under the same lock, so a stored + * version matching ours implies the cache beside it uses the current schema. On a + * mismatch the cache is unusable but still parses -- a removed field reads back as + * its default rather than failing -- so it has to be discarded, not just resynced. + */ + logger.debug( + "NEED_SYNC: sync meta version mismatch: expected={}, actual={}", + SYNC_META_VERSION, + stored.metaVersion, + ) + discardSyncFiles(projectDir) + return true + } + + // Built only once the cheap version gate has passed: it walks every watched file. + val draft = createSyncMeta(projectDir, includeChecksum = false) + val draftFilePaths = draft.watchedFilesList.map { it.relativePath }.toSet() val storedFilePaths = stored.watchedFilesList.map { it.relativePath }.toSet() if (draftFilePaths != storedFilePaths) { @@ -322,7 +575,8 @@ object ProjectSyncHelper { val hashResults = computeHashes(needsHash) for ((draft, computedSha) in hashResults) { val stored = storedMap[draft.relativePath] ?: continue - if (stored.sha256 == null) { + // sha256 is an optional string, so an absent one reads back as empty, never as null. + if (stored.sha256.isEmpty()) { // stored metadata didn't have sha256, so we can't compare // require sync logger.debug( @@ -348,6 +602,60 @@ object ProjectSyncHelper { return false } + /** + * Delete the sync metadata and project model cache files for the given project directory. + * + * Taken under the same lock the sync writes them under. Failing to acquire it means a sync is + * already in flight and about to replace both files, so the deletion is skipped. Acquiring it + * does not mean the files are still stale, so staleness is rechecked under the lock. + */ + private suspend fun discardSyncFiles(projectDir: File) { + withContext(Dispatchers.IO) { + try { + val locked = + tryUseSyncLock(projectDir, DISCARD_LOCK_TIMEOUT_MS) { + val syncMetaFile = syncMetaFileForProject(projectDir) + + /* + * Staleness was decided outside the lock, and a sync can complete while we + * wait here. Re-read before deleting, or a discard takes out the fresh + * files that sync just wrote. + */ + if (isSyncMetaVersionCurrent(syncMetaFile)) { + logger.debug("Sync files were rewritten while waiting for the lock, keeping them") + } else { + deleteOrWarn(syncMetaFile) + deleteOrWarn(cacheFileForProject(projectDir)) + } + } + + if (!locked) { + logger.debug("Sync lock unavailable, leaving the stale sync files to the running sync") + } + } catch (err: CancellationException) { + throw err + } catch (err: Throwable) { + /* + * Creating or opening the lock file fails on a read-only volume, and the re-read + * under the lock can fail on a corrupt file. Callers treat checkSyncNeeded as a + * boolean query and rethrow anything else, so letting either escape would crash + * the project open instead of resyncing it. + */ + logger.warn("Failed to discard the stale sync files", err) + } + } + } + + /** + * Delete [file], warning if it survives. A stale file left behind is read back on the next + * launch, so a silent failure here is worth a log line. + */ + private fun deleteOrWarn(file: File) { + if (!file.delete() && file.exists()) { + logger.warn("Failed to delete stale sync file: {}", file) + } + } + private suspend fun computeHashes(files: List): Map = coroutineScope { withContext(hashDispatcher) { @@ -398,7 +706,7 @@ object ProjectSyncHelper { } val projectDir = projectDir.toRealPath() return SyncMeta( - metaVersion = "1", + metaVersion = SYNC_META_VERSION, rootProjectPath = projectDir.pathString, syncTime = System.currentTimeMillis().toString(), watchedFilesList = createWatchedFilesList(projectDir, includeChecksum), @@ -488,8 +796,11 @@ object ProjectSyncHelper { */ suspend fun loadSyncMetaFromFile(file: File): SyncMetaModels.SyncMeta = withContext(Dispatchers.IO) { - file.inputStream().buffered().use { fileIn -> - SyncMetaModels.SyncMeta.parseFrom(fileIn) - } + readSyncMeta(file) + } + + private fun readSyncMeta(file: File): SyncMetaModels.SyncMeta = + file.inputStream().buffered().use { fileIn -> + SyncMetaModels.SyncMeta.parseFrom(fileIn) } }