From 59b3bc33693e104d92629142d7882b93d87721c0 Mon Sep 17 00:00:00 2001 From: Pablo Rodriguez Defino Date: Wed, 2 Dec 2026 03:09:55 +0000 Subject: [PATCH] [Rust SDK] Share Cargo workspace builds and run crate test binaries in parallel Compile all workspace test binaries once in `compileWorkspaceTests` (`cargo test --workspace --no-run --message-format=json`) and record their executable paths in a manifest. Run each crate's compiled test binaries in parallel with Gradle's `WorkerExecutor`, bounded by `-PtestConcurrency` (default 4), and run workspace doctests once in `testWorkspaceDoctests`. Keep `-Ppkg=` focused on one crate with native `cargo test -p `, honoring `-PonlyFeatures` and `-PtestArgs`. Compute unified workspace default feature closures in `CargoWorkspace` so manifest-mode `test_` task inputs and cache keys match workspace compilation. Run `fmtCheck`, `clippy`, and `clippyFix` through Gradle's `WorkerExecutor`. Add `clippyLintReport` to count candidate lint warnings, and add `cleanWorkspace` (`cargo clean --workspace`) to remove workspace build artifacts while keeping dependency caches. --- .../beam/gradle/rust/CargoWorkspace.groovy | 257 +++++++- .../beam/gradle/rust/RustSdkBuild.groovy | 45 +- .../rust/workspace/RustLintTasks.groovy | 339 ++++++++-- .../rust/workspace/RustTestTasks.groovy | 619 +++++++++++++++--- 4 files changed, 1122 insertions(+), 138 deletions(-) diff --git a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/CargoWorkspace.groovy b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/CargoWorkspace.groovy index 327049f18b9c..1c79da919408 100644 --- a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/CargoWorkspace.groovy +++ b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/CargoWorkspace.groovy @@ -53,16 +53,24 @@ class CargoWorkspace { /** The directory of each crate, by package name. */ final Map crateDir = new LinkedHashMap<>() - /** The workspace crates that each crate depends on, the crate included. */ + /** The package name of each crate directory, by canonical path. */ + final Map dirToPkg = new LinkedHashMap<>() + /** The workspace crates that each crate depends on under its own features, the crate included. */ final Map> crateClosure = new LinkedHashMap<>() + /** The workspace crates that each crate depends on under unified workspace features, the crate included. */ + final Map> crateWorkspaceClosure = new LinkedHashMap<>() + /** The features active on each crate under unified workspace default resolution. */ + final Map> workspaceActiveFeatures = new LinkedHashMap<>() /** The crates, each one after the crates that it depends on. */ final List topoOrder = [] - private final Map dirToPkg = [:] private final Map workspaceDeps = [:] private final Map>> crateFeatures = [:] private final Map> crateDeps = [:] + private final Map> crateBuildDeps = [:] private final Map> crateDevDeps = [:] + private final Map> crateOptionalDeps = [:] + private final Map> crateExplicitDepSyntax = [:] private final Map> crateTestRequiredFeatures = [:] /** @@ -74,12 +82,14 @@ class CargoWorkspace { readWorkspaceDeps(new File(rustDir, 'Cargo.toml')) memberTomls.each { File toml -> readPackageName(toml) } crateDir.each { String pkg, File dir -> readManifest(pkg, dir) } + resolveWorkspaceFeatures() crateDir.keySet().each { String pkg -> String features = (selectedPkg == pkg && onlyFeatures != null) ? onlyFeatures : null - crateClosure[pkg] = new ClosureResolver(pkg, features).resolve() + crateClosure[pkg] = new ClosureResolver(pkg, features, null).resolve() + crateWorkspaceClosure[pkg] = new ClosureResolver(pkg, null, workspaceActiveFeatures).resolve() } Set visited = new HashSet<>() - crateDir.keySet().sort().each { String pkg -> visitTopo(pkg, visited) } + crateDir.keySet().toList().sort().each { String pkg -> visitTopo(pkg, visited) } } /** The library inputs of a crate. They exclude tests, benches and examples. */ @@ -156,7 +166,7 @@ class CargoWorkspace { private void readWorkspaceDeps(File rootToml) { parseToml(rootToml).each { TomlEntry entry -> - if (entry.section != 'workspace.dependencies' || !entry.line.contains('path =')) { + if (entry.section != 'workspace.dependencies' || !entry.line.contains('=')) { return } String[] kv = entry.line.split('=', 2) @@ -167,7 +177,7 @@ class CargoWorkspace { } workspaceDeps[alias] = new WorkspaceDep( pkg: firstGroup(rhs, /package\s*=\s*"([^"]+)"/) ?: alias, - defaultFeatures: !rhs.contains('default-features = false'), + defaultFeatures: !(rhs =~ /\bdefault-features\s*=\s*false\b/).find(), features: featureArray(rhs)) } } @@ -186,19 +196,39 @@ class CargoWorkspace { private void readManifest(String pkg, File dir) { crateFeatures[pkg] = [:] crateDeps[pkg] = [] + crateBuildDeps[pkg] = [] crateDevDeps[pkg] = [] + crateOptionalDeps[pkg] = new LinkedHashSet<>() + crateExplicitDepSyntax[pkg] = new LinkedHashSet<>() crateTestRequiredFeatures[pkg] = [] parseToml(new File(dir, 'Cargo.toml')).each { TomlEntry entry -> String section = entry.section String line = entry.line if (section == 'features' && line.contains('=')) { String[] kv = line.split('=', 2) - crateFeatures[pkg][kv[0].trim()] = quotedStrings(kv[1]) - } else if (section == 'dependencies' || section == 'build-dependencies') { + List tokens = quotedStrings(kv[1]) + crateFeatures[pkg][kv[0].trim()] = tokens + tokens.each { String t -> + if (t.startsWith('dep:')) { + crateExplicitDepSyntax[pkg].add(t.substring(4)) + } + } + } else if (section == 'dependencies') { + if (line.contains('=')) { + String[] kv = line.split('=', 2) + if ((kv[1] =~ /\boptional\s*=\s*true\b/).find()) { + crateOptionalDeps[pkg].add(kv[0].trim()) + } + } Dep dep = parseDep(dir, line) if (dep != null) { crateDeps[pkg].add(dep) } + } else if (section == 'build-dependencies') { + Dep dep = parseDep(dir, line) + if (dep != null) { + crateBuildDeps[pkg].add(dep) + } } else if (section == 'dev-dependencies') { Dep dep = parseDep(dir, line) if (dep != null) { @@ -210,6 +240,157 @@ class CargoWorkspace { } } + private Set implicitOptionalFeaturesOf(String pkg) { + Set opt = new LinkedHashSet<>(crateOptionalDeps[pkg] ?: Collections.emptySet()) + opt.removeAll(crateExplicitDepSyntax[pkg] ?: Collections.emptySet()) + return opt + } + + /** Computes the features active on each crate under unified workspace default resolution. */ + private void resolveWorkspaceFeatures() { + Map> implicitOpt = new LinkedHashMap<>() + crateDir.keySet().each { String pkg -> implicitOpt[pkg] = implicitOptionalFeaturesOf(pkg) } + new WorkspaceFeatureResolver( + crateDir.keySet(), crateDeps, crateDevDeps, crateFeatures, implicitOpt, workspaceActiveFeatures).resolve() + } + + private static class WorkspaceFeatureResolver { + private final Set pkgs + private final Map> crateDeps + private final Map> crateDevDeps + private final Map>> crateFeatures + private final Map> implicitOptionalFeatures + private final Map> activeFeatures + private final Set activatedPkgs = new HashSet<>() + private final Set activatedEdges = new HashSet<>() + private final Map> activeAliases = new LinkedHashMap<>() + private final Map>> pendingWeak = new LinkedHashMap<>() + + WorkspaceFeatureResolver( + Set pkgs, + Map> crateDeps, + Map> crateDevDeps, + Map>> crateFeatures, + Map> implicitOptionalFeatures, + Map> activeFeatures) { + this.pkgs = pkgs + this.crateDeps = crateDeps + this.crateDevDeps = crateDevDeps + this.crateFeatures = crateFeatures + this.implicitOptionalFeatures = implicitOptionalFeatures + this.activeFeatures = activeFeatures + } + + void resolve() { + for (String pkg : pkgs) { + activeFeatures[pkg] = new LinkedHashSet<>() + activeAliases[pkg] = new HashSet<>() + pendingWeak[pkg] = new LinkedHashMap<>() + } + for (String pkg : pkgs) { + enableFeat(pkg, 'default') + activatePkgDeps(pkg) + for (Dep d : (crateDevDeps[pkg] ?: new ArrayList())) { + if (!d.optional) { + activateDep(pkg, d) + } + } + } + } + + private void ensurePkgMaps(String pkg) { + activeFeatures.computeIfAbsent(pkg, { new LinkedHashSet() }) + activeAliases.computeIfAbsent(pkg, { new HashSet() }) + pendingWeak.computeIfAbsent(pkg, { new LinkedHashMap>() }) + } + + private void activatePkgDeps(String pkg) { + if (!activatedPkgs.add(pkg)) { + return + } + for (Dep d : (crateDeps[pkg] ?: new ArrayList())) { + if (!d.optional) { + activateDep(pkg, d) + } + } + } + + private void activateDep(String fromPkg, Dep d) { + ensurePkgMaps(fromPkg) + ensurePkgMaps(d.targetPkg) + activatePkgDeps(d.targetPkg) + if (activeAliases[fromPkg].add(d.alias)) { + Set waiting = pendingWeak[fromPkg].remove(d.alias) + if (waiting != null) { + for (String wf : waiting) { + enableFeat(d.targetPkg, wf) + } + } + } + String edgeKey = "${fromPkg}->${d.alias}:${d.targetPkg}:${d.defaultFeatures}:${d.features.join(',')}" + if (!activatedEdges.add(edgeKey)) { + return + } + if (d.defaultFeatures) { + enableFeat(d.targetPkg, 'default') + } + for (String f : d.features) { + enableFeat(d.targetPkg, f) + } + } + + private void enableFeat(String pkg, String feat) { + ensurePkgMaps(pkg) + if (!activeFeatures[pkg].add(feat)) { + return + } + List deps = crateDeps[pkg] ?: new ArrayList() + if (feat in (implicitOptionalFeatures[pkg] ?: Collections.emptySet())) { + for (Dep d : deps) { + if (d.optional && d.alias == feat) { + activateDep(pkg, d) + } + } + } + List tokens = (crateFeatures[pkg] ?: new HashMap>())[feat] + if (tokens == null) { + return + } + for (String token : tokens) { + if (token.startsWith('dep:')) { + String depAlias = token.substring(4) + for (Dep d : deps) { + if (d.alias == depAlias) { + activateDep(pkg, d) + } + } + } else if (token.contains('/')) { + String[] parts = token.split('/', 2) + boolean weak = parts[0].endsWith('?') + String depAlias = weak ? parts[0].substring(0, parts[0].length() - 1) : parts[0] + List matching = deps.findAll { Dep d -> d.alias == depAlias } + if (!weak) { + if (depAlias in (implicitOptionalFeatures[pkg] ?: Collections.emptySet())) { + enableFeat(pkg, depAlias) + } + for (Dep d : matching) { + activateDep(pkg, d) + enableFeat(d.targetPkg, parts[1]) + } + } else if (depAlias in activeAliases[pkg]) { + for (Dep d : matching) { + enableFeat(d.targetPkg, parts[1]) + } + } else { + pendingWeak[pkg].computeIfAbsent(depAlias, { new LinkedHashSet() }).add(parts[1]) + } + } else { + enableFeat(pkg, token) + } + } + } + } + /** Returns the dependency of this line, or null if the target is not a workspace crate. */ private Dep parseDep(File memberDir, String line) { if (!line.contains('=')) { @@ -218,7 +399,7 @@ class CargoWorkspace { String[] kv = line.split('=', 2) String alias = kv[0].trim() String rhs = kv[1].trim() - boolean fromWorkspace = rhs.contains('workspace = true') + boolean fromWorkspace = (rhs =~ /\bworkspace\s*=\s*true\b/).find() String targetPkg = null String packageName = firstGroup(rhs, /package\s*=\s*"([^"]+)"/) String path = firstGroup(rhs, /path\s*=\s*"([^"]+)"/) @@ -233,11 +414,15 @@ class CargoWorkspace { return null } WorkspaceDep shared = fromWorkspace ? workspaceDeps[alias] : null + String memberDefaultFeatures = firstGroup(rhs, /\bdefault-features\s*=\s*(true|false)\b/) + boolean defaultFeatures = memberDefaultFeatures != null + ? memberDefaultFeatures == 'true' + : (shared == null || shared.defaultFeatures) return new Dep( alias: alias, targetPkg: targetPkg, - optional: rhs.contains('optional = true'), - defaultFeatures: !rhs.contains('default-features = false') && (shared == null || shared.defaultFeatures), + optional: (rhs =~ /\boptional\s*=\s*true\b/).find(), + defaultFeatures: defaultFeatures, features: (featureArray(rhs) + (shared == null ? new ArrayList() : shared.features)).unique()) } @@ -245,7 +430,7 @@ class CargoWorkspace { if (!visited.add(pkg)) { return } - crateClosure[pkg].each { String dep -> + crateClosure[pkg].toList().sort().each { String dep -> if (dep != pkg && crateDir.containsKey(dep)) { visitTopo(dep, visited) } @@ -257,13 +442,17 @@ class CargoWorkspace { private class ClosureResolver { private final String rootPkg private final String onlyFeatures + private final Map> unifiedFeatures private final Set activeCrates = new LinkedHashSet<>() private final Set enabledFeatures = new LinkedHashSet<>() private final Set activatedEdges = new LinkedHashSet<>() + private final Map> activeAliases = new LinkedHashMap<>() + private final Map>> pendingWeak = new LinkedHashMap<>() - ClosureResolver(String rootPkg, String onlyFeatures) { + ClosureResolver(String rootPkg, String onlyFeatures, Map> unifiedFeatures) { this.rootPkg = rootPkg this.onlyFeatures = onlyFeatures + this.unifiedFeatures = unifiedFeatures } Set resolve() { @@ -276,13 +465,16 @@ class CargoWorkspace { return } depsOf(pkg).findAll { Dep d -> !d.optional }.each { Dep d -> activateEdge(pkg, d) } + if (unifiedFeatures != null) { + (unifiedFeatures[pkg] ?: Collections.emptySet()).each { String f -> enableFeature(pkg, f) } + } if (pkg != rootPkg) { return } (crateDevDeps[pkg] ?: new ArrayList()).findAll { Dep d -> !d.optional } .each { Dep d -> activateEdge(pkg, d) } if (onlyFeatures != null) { - onlyFeatures.split(',').collect { String f -> f.trim() }.findAll { String f -> !f.isEmpty() } + onlyFeatures.split(/[,\s]+/).collect { String f -> f.trim() }.findAll { String f -> !f.isEmpty() } .each { String f -> enableFeature(pkg, f) } } else { enableFeature(pkg, 'default') @@ -291,6 +483,15 @@ class CargoWorkspace { } private void activateEdge(String fromPkg, Dep d) { + Set aliases = activeAliases.computeIfAbsent(fromPkg, { new HashSet() }) + if (aliases.add(d.alias)) { + Set waiting = pendingWeak[fromPkg]?.remove(d.alias) + if (waiting != null) { + for (String wf : waiting) { + enableFeature(d.targetPkg, wf) + } + } + } String edgeKey = "${fromPkg}->${d.alias}:${d.targetPkg}:${d.defaultFeatures}:${d.features.join(',')}" if (!activatedEdges.add(edgeKey)) { return @@ -307,7 +508,9 @@ class CargoWorkspace { if (!enabledFeatures.add("${pkg}:${feature}".toString())) { return } - depsOf(pkg).findAll { Dep d -> d.optional && d.alias == feature }.each { Dep d -> activateEdge(pkg, d) } + if (feature in implicitOptionalFeaturesOf(pkg)) { + depsOf(pkg).findAll { Dep d -> d.optional && d.alias == feature }.each { Dep d -> activateEdge(pkg, d) } + } List tokens = (crateFeatures[pkg] ?: new HashMap>())[feature] (tokens ?: new ArrayList()).each { String token -> if (token.startsWith('dep:')) { @@ -315,12 +518,23 @@ class CargoWorkspace { depsOf(pkg).findAll { Dep d -> d.alias == depAlias }.each { Dep d -> activateEdge(pkg, d) } } else if (token.contains('/')) { String[] parts = token.split('/', 2) - String depAlias = parts[0].replace('?', '') - depsOf(pkg).findAll { Dep d -> d.alias == depAlias }.each { Dep d -> - if (!parts[0].endsWith('?')) { + boolean weak = parts[0].endsWith('?') + String depAlias = weak ? parts[0].substring(0, parts[0].length() - 1) : parts[0] + List matching = depsOf(pkg).findAll { Dep d -> d.alias == depAlias } + if (!weak) { + if (depAlias in implicitOptionalFeaturesOf(pkg)) { + enableFeature(pkg, depAlias) + } + matching.each { Dep d -> activateEdge(pkg, d) + enableFeature(d.targetPkg, parts[1]) } - enableFeature(d.targetPkg, parts[1]) + } else if (depAlias in (activeAliases[pkg] ?: Collections.emptySet())) { + matching.each { Dep d -> enableFeature(d.targetPkg, parts[1]) } + } else { + pendingWeak.computeIfAbsent(pkg, { new LinkedHashMap>() }) + .computeIfAbsent(depAlias, { new LinkedHashSet() }) + .add(parts[1]) } } else { enableFeature(pkg, token) @@ -329,7 +543,10 @@ class CargoWorkspace { } private List depsOf(String pkg) { - return crateDeps[pkg] ?: new ArrayList() + List all = new ArrayList<>() + all.addAll(crateDeps[pkg] ?: new ArrayList()) + all.addAll(crateBuildDeps[pkg] ?: new ArrayList()) + return all } } } diff --git a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/RustSdkBuild.groovy b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/RustSdkBuild.groovy index 225b845f3235..a245f5584e9d 100644 --- a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/RustSdkBuild.groovy +++ b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/RustSdkBuild.groovy @@ -18,17 +18,31 @@ package org.apache.beam.gradle.rust import groovy.transform.CompileStatic +import javax.inject.Inject import org.gradle.api.Project +import org.gradle.api.Task import org.gradle.api.file.ConfigurableFileTree import org.gradle.api.tasks.Exec import org.gradle.api.tasks.TaskProvider +import org.gradle.workers.WorkerExecutor /** The settings that the task groups of the Rust SDK build share. */ @CompileStatic class RustSdkBuild { + + /** Provides Gradle's {@link WorkerExecutor} to non-task classes. */ + abstract static class RustWorkerAccess { + @Inject + RustWorkerAccess() {} + + @Inject + abstract WorkerExecutor getWorkerExecutor() + } + final Project project final RustSdkExtension extension final BeamVersions versions + final WorkerExecutor workerExecutor /** The root of the Cargo workspace. */ final File rustDir final CargoWorkspace workspace @@ -48,19 +62,24 @@ class RustSdkBuild { final List modelProtoDirs final List workspaceRootFiles + final File workspaceTestManifest /** The {@code test_} task of each crate. */ - final Map> testTasks = new LinkedHashMap<>() + final Map> testTasks = new LinkedHashMap<>() RustSdkBuild(Project project, RustSdkExtension extension) { this.project = project this.extension = extension versions = new BeamVersions(project) + workerExecutor = project.objects.newInstance(RustWorkerAccess).workerExecutor rustDir = new File(project.rootDir, 'sdks/rust') selectedPkg = (project.findProperty('pkg') ?: project.findProperty('package'))?.toString() onlyFeatures = project.findProperty('onlyFeatures')?.toString() featureScope = (selectedPkg != null && onlyFeatures != null) - ? ['--no-default-features', '--features', onlyFeatures] : new ArrayList() + ? (onlyFeatures.trim().isEmpty() + ? ['--no-default-features'] + : ['--no-default-features', '--features', onlyFeatures]) + : new ArrayList() cargoScope = (selectedPkg != null ? ['-p', selectedPkg] : workspaceScope) + featureScope testArgs = project.findProperty('testArgs')?.toString()?.tokenize() ?: new ArrayList() noFailFast = project.gradle.startParameter.continueOnFailure @@ -70,7 +89,7 @@ class RustSdkBuild { memberTomls.include('**/Cargo.toml') memberTomls.exclude('Cargo.toml', 'target/**', 'container/**', 'build/**', 'examples/build/**') workspace = new CargoWorkspace( - rustDir, memberTomls.files.sort { File f -> f.absolutePath }, selectedPkg, onlyFeatures) + rustDir, memberTomls.files.toList().sort { File f -> f.absolutePath }, selectedPkg, onlyFeatures) modelProtoDirs = [ 'model/pipeline/src/main/proto', @@ -82,18 +101,31 @@ class RustSdkBuild { new File(rustDir, 'Cargo.lock'), new File(project.rootDir, 'gradle.properties'), ] + workspaceTestManifest = buildFile('test-results/cargo/workspace-test-manifest.tsv') } /** Registers an Exec task that runs {@code cargo } in the workspace root. */ TaskProvider cargoTask(String name, String taskGroup, String text, List args) { + Map env = versions.cargoEnv() return project.tasks.register(name, Exec) { Exec task -> task.group = taskGroup task.description = text task.workingDir(rustDir) + task.environment(env) task.commandLine(['cargo'] + args) } } + /** The Cargo target directory, honoring {@code CARGO_TARGET_DIR} when set. */ + File cargoTargetDir() { + String envDir = System.getenv('CARGO_TARGET_DIR')?.trim() + if (envDir) { + File dir = new File(envDir) + return dir.isAbsolute() ? dir : new File(rustDir, envDir) + } + return new File(rustDir, 'target') + } + /** The crates of the default {@code test}: all but the benchmark crates. */ List defaultPackages() { List benchmarks = extension.benchmarkPackages.get() @@ -109,6 +141,13 @@ class RustSdkBuild { } } + /** The library inputs of these crates. */ + List libInputs(Collection packages) { + List inputs = [] + packages.each { String pkg -> inputs.addAll(workspace.libInputFiles(pkg)) } + return inputs + } + /** The library and test inputs of these crates. */ List libAndTestInputs(Collection packages) { List inputs = [] diff --git a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustLintTasks.groovy b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustLintTasks.groovy index 618ab2fc031f..af56e65ec853 100644 --- a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustLintTasks.groovy +++ b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustLintTasks.groovy @@ -17,18 +17,86 @@ */ package org.apache.beam.gradle.rust.workspace +import groovy.json.JsonException +import groovy.json.JsonSlurper +import groovy.transform.CompileDynamic import groovy.transform.CompileStatic import org.apache.beam.gradle.rust.CargoWorkspace import org.apache.beam.gradle.rust.RustSdkBuild import org.gradle.api.Action +import org.gradle.api.GradleException +import org.gradle.api.Task +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.MapProperty +import org.gradle.api.provider.Property import org.gradle.api.tasks.Exec import org.gradle.api.tasks.PathSensitivity -import org.gradle.process.ExecSpec +import org.gradle.workers.WorkAction +import org.gradle.workers.WorkParameters /** The build, format, lint and clean tasks. */ @CompileStatic class RustLintTasks { + /** Parameters for {@link ExecCheckWorkAction}. */ + static interface ExecCheckWorkParams extends WorkParameters { + Property getWorkingDir() + ListProperty getCommands() + ListProperty getLabels() + MapProperty getEnvironment() + RegularFileProperty getStampFile() + Property getStreamLive() + } + + /** Runs one or more check commands sequentially through Gradle's worker executor and writes a stamp file. */ + abstract static class ExecCheckWorkAction implements WorkAction { + @Override + void execute() { + ExecCheckWorkParams p = parameters + List encodedCommands = p.commands.get() + List labels = p.labels.get() + boolean stream = p.streamLive.get() + File stamp = p.stampFile.asFile.orNull + for (int i = 0; i < encodedCommands.size(); i++) { + List cmd = encodedCommands[i].split('\u0000', -1).toList() + ProcessBuilder pb = new ProcessBuilder(cmd) + pb.directory(p.workingDir.get()) + pb.redirectErrorStream(true) + pb.environment().putAll(p.environment.get()) + Process proc = pb.start() + StringBuilder captured = new StringBuilder() + int exit + try { + proc.inputStream.eachLine('UTF-8') { String line -> + if (stream) { + System.out.println(line) + } else { + captured.append(line).append('\n') + } + } + exit = proc.waitFor() + } finally { + if (proc.alive) { + proc.destroyForcibly() + } + } + if (exit != 0) { + if (!stream && captured.length() > 0) { + System.err.print(captured.toString()) + } + if (stamp != null) { + stamp.delete() + } + throw new GradleException("${labels[i]} failed with exit code ${exit}") + } + } + if (stamp != null) { + RustSdkBuild.writeStamp(stamp) + } + } + } + /** The lints that test and benchmark code can break. clippy.toml exempts {@code #[cfg(test)]}. */ private static final List TEST_CLIPPY_ALLOWS = [ 'unwrap_used', @@ -41,17 +109,22 @@ class RustLintTasks { registerBuildWorkspace(build) registerFmt(build) registerClippy(build) - build.cargoTask('cleanSdk', 'Build', 'Remove the cargo target directory', ['clean']) + registerClippyExtras(build) + registerCleanTasks(build) } private static void registerBuildWorkspace(RustSdkBuild build) { build.cargoTask('buildWorkspace', 'Build', - 'Compile all crates in the Rust workspace but the benchmarks (or one crate with -Ppkg=)', + 'Compile all crates in the Rust workspace (or one crate with -Ppkg=)', ['build'] + build.cargoScope).configure { Exec task -> String pkg = build.selectedPkg CargoWorkspace workspace = build.workspace + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix', 'clippy', 'clippyLintReport') task.inputs.property('beamSdkVersion', build.versions.sdkVersion) + task.inputs.property('beamReleaseVersion', build.versions.releaseVersion) + task.inputs.property('beamVersion', build.versions.beamVersion) task.inputs.property('cargoScope', build.cargoScope) + task.inputs.property('cargoTargetDir', build.cargoTargetDir().canonicalPath) task.inputs.files(build.workspaceRootFiles).withPathSensitivity(PathSensitivity.RELATIVE) task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) task.inputs.files(build.project.provider { @@ -61,57 +134,247 @@ class RustLintTasks { inputs.addAll(build.testInputFiles(pkg)) return inputs } - return build.libAndTestInputs(build.defaultPackages()) + return build.libAndTestInputs(build.workspace.topoOrder) }).withPathSensitivity(PathSensitivity.RELATIVE) + String featureKey = build.onlyFeatures != null + ? (build.onlyFeatures.trim().isEmpty() ? 'none' : build.onlyFeatures) + : 'default' String buildKey = pkg != null - ? "${pkg}-${build.onlyFeatures ?: 'default'}".replaceAll('[^a-zA-Z0-9_-]', '_') + ? "${pkg}-${featureKey}".replaceAll('[^a-zA-Z0-9_-]', '_') : 'workspace' File stampFile = build.buildFile("test-results/cargo/build-${buildKey}.txt") task.outputs.file(stampFile) // Cargo decides what to compile; Gradle only skips the call when no input changed. - task.outputs.upToDateWhen { new File(build.rustDir, 'target').exists() } + task.outputs.upToDateWhen { build.cargoTargetDir().exists() } task.doLast { RustSdkBuild.writeStamp(stampFile) } } } private static void registerFmt(RustSdkBuild build) { - build.cargoTask('fmtCheck', 'Verification', 'Verify formatting (cargo fmt --check)', - ['fmt', '--check']).configure { Exec task -> - task.inputs.files(new File(build.rustDir, 'rustfmt.toml'), new File(build.rustDir, 'Cargo.toml')) - .withPathSensitivity(PathSensitivity.RELATIVE) - task.inputs.files(build.libAndTestInputs(build.workspace.topoOrder)) - .withPathSensitivity(PathSensitivity.RELATIVE) - File stampFile = build.buildFile('test-results/cargo/fmtCheck.txt') - task.outputs.file(stampFile) - task.outputs.cacheIf { true } - task.doLast { RustSdkBuild.writeStamp(stampFile) } - } build.cargoTask('fmt', 'Verification', 'Format all Rust code (cargo fmt)', ['fmt']) + build.project.tasks.register('fmtCheck') { Task task -> + task.group = 'Verification' + task.description = 'Verify formatting (cargo fmt --check)' + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix') + task.inputs.files(new File(build.rustDir, 'rustfmt.toml'), new File(build.rustDir, 'Cargo.toml')) + .withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.libAndTestInputs(build.workspace.topoOrder)) + .withPathSensitivity(PathSensitivity.RELATIVE) + File stampFile = build.buildFile('test-results/cargo/fmtCheck.txt') + task.outputs.file(stampFile) + task.outputs.cacheIf { true } + task.doLast { + stampFile.delete() + build.workerExecutor.noIsolation().submit(ExecCheckWorkAction.class, { ExecCheckWorkParams p -> + p.workingDir.set(build.rustDir) + p.commands.set([['cargo', 'fmt', '--check'].join('\u0000')]) + p.labels.set(['cargo fmt --check']) + p.environment.set(build.versions.cargoEnv()) + p.stampFile.set(stampFile) + p.streamLive.set(false) + } as Action) + } + } } private static void registerClippy(RustSdkBuild build) { - build.cargoTask('clippy', 'Verification', 'Run clippy on all targets (-D warnings)', - ['clippy'] + build.workspaceScope + ['--lib', '--bins', '--examples', '--', '-D', 'warnings']) - .configure { Exec task -> - task.mustRunAfter('fmtCheck') - task.inputs.property('beamSdkVersion', build.versions.sdkVersion) - task.inputs.files(build.workspaceRootFiles + [new File(build.rustDir, 'clippy.toml')]) - .withPathSensitivity(PathSensitivity.RELATIVE) - task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) - task.inputs.files(build.project.provider { build.libAndTestInputs(build.defaultPackages()) }) - .withPathSensitivity(PathSensitivity.RELATIVE) - File stampFile = build.buildFile('test-results/cargo/clippy.txt') - task.outputs.file(stampFile) - task.outputs.cacheIf { true } - task.doLast { - build.project.exec({ ExecSpec spec -> - spec.workingDir(build.rustDir) - spec.environment(build.versions.cargoEnv()) - spec.commandLine(['cargo', 'clippy'] + build.workspaceScope + - ['--tests', '--benches', '--', '-D', 'warnings'] + TEST_CLIPPY_ALLOWS) - } as Action) - RustSdkBuild.writeStamp(stampFile) + build.project.tasks.register('clippy') { Task task -> + task.group = 'Verification' + task.description = 'Run clippy on all targets (-D warnings)' + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix') + task.inputs.property('beamSdkVersion', build.versions.sdkVersion) + task.inputs.property('beamReleaseVersion', build.versions.releaseVersion) + task.inputs.property('beamVersion', build.versions.beamVersion) + task.inputs.files(build.workspaceRootFiles + [new File(build.rustDir, 'clippy.toml')]) + .withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.project.provider { build.libAndTestInputs(build.workspace.topoOrder) }) + .withPathSensitivity(PathSensitivity.RELATIVE) + File stampFile = build.buildFile('test-results/cargo/clippy.txt') + task.outputs.file(stampFile) + task.outputs.cacheIf { true } + task.doLast { + stampFile.delete() + Map env = build.versions.cargoEnv() + List pass1 = ['cargo', 'clippy'] + build.workspaceScope + + ['--lib', '--bins', '--examples', '--', '-D', 'warnings'] + List pass2 = ['cargo', 'clippy'] + build.workspaceScope + + ['--tests', '--benches', '--', '-D', 'warnings'] + TEST_CLIPPY_ALLOWS + build.workerExecutor.noIsolation().submit(ExecCheckWorkAction.class, { ExecCheckWorkParams p -> + p.workingDir.set(build.rustDir) + p.commands.set([pass1.join('\u0000'), pass2.join('\u0000')]) + p.labels.set([ + 'cargo clippy (--lib --bins --examples)', + 'cargo clippy (--tests --benches)', + ]) + p.environment.set(env) + p.stampFile.set(stampFile) + p.streamLive.set(true) + } as Action) + } + } + } + + private static void registerClippyExtras(RustSdkBuild build) { + build.project.tasks.register('clippyFix') { Task task -> + task.group = 'Verification' + task.description = 'Apply the machine-applicable lint fixes to all targets (cargo clippy --fix)' + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt') + task.doLast { + List fixFlags = ['--fix', '--allow-dirty', '--allow-staged', '--allow-no-vcs'] + Map env = build.versions.cargoEnv() + List pass1 = ['cargo', 'clippy'] + build.workspaceScope + + ['--lib', '--bins', '--examples'] + fixFlags + List pass2 = ['cargo', 'clippy'] + build.workspaceScope + + ['--tests', '--benches'] + fixFlags + ['--'] + TEST_CLIPPY_ALLOWS + build.workerExecutor.noIsolation().submit(ExecCheckWorkAction.class, { ExecCheckWorkParams p -> + p.workingDir.set(build.rustDir) + p.commands.set([pass1.join('\u0000'), pass2.join('\u0000')]) + p.labels.set([ + 'cargo clippy --fix (--lib --bins --examples)', + 'cargo clippy --fix (--tests --benches)', + ]) + p.environment.set(env) + p.streamLive.set(true) + } as Action) + } + } + + File report = build.buildFile('reports/clippy-lints.txt') + build.project.tasks.register('clippyLintReport') { Task task -> + task.group = 'Verification' + task.description = 'Count the warnings of candidate clippy lints on all targets ' + + '(-PclippyLints=match_bool,expect_used,...); writes build/reports/clippy-lints.txt' + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix', 'clippy') + task.outputs.file(report) + task.outputs.upToDateWhen { false } + task.doLast { + report.delete() + List lints = (build.project.findProperty('clippyLints') ?: '') + .toString() + .tokenize(',') + .collect { String l -> l.trim().replaceFirst(/^clippy::/, '').replace('-', '_') } + .findAll { String l -> !l.isEmpty() } + .unique() + if (lints.isEmpty()) { + throw new GradleException( + 'Set -PclippyLints=, (individual clippy lint names, with or without the clippy:: prefix).') + } + List lintFlags = lints.collectMany { String l -> ['-W', "clippy::${l}".toString()] } + ProcessBuilder pb = new ProcessBuilder( + ['cargo', 'clippy'] + build.workspaceScope + + ['--all-targets', '--keep-going', '--message-format=json', '--'] + lintFlags) + pb.directory(build.rustDir) + pb.environment().putAll(build.versions.cargoEnv()) + Process proc = pb.start() + StringBuilder err = new StringBuilder() + Thread errThread = Thread.start { + proc.errorStream.eachLine('UTF-8') { String line -> err.append(line).append('\n') } + } + String rawJson + int exitValue + try { + rawJson = proc.inputStream.getText('UTF-8') + exitValue = proc.waitFor() + } finally { + if (proc.alive) { + proc.destroyForcibly() } + errThread.join() + } + writeClippyLintReport(task, lints, rawJson, err.toString(), exitValue, report) + } + } + } + + private static Object parseJsonLine(JsonSlurper slurper, String line) { + try { + return slurper.parseText(line) + } catch (JsonException ignored) { + return null + } + } + + @CompileDynamic + private static void writeClippyLintReport( + Task task, List lints, String rawJson, String stderrText, int exitValue, File report) { + JsonSlurper slurper = new JsonSlurper() + List messages = rawJson.readLines() + .collect { String line -> line.trim() } + .findAll { String line -> line.startsWith('{') } + .collect { String line -> parseJsonLine(slurper, line) } + .findAll { def msg -> msg != null && msg.reason == 'compiler-message' } + List invalidLintRendered = messages + .findAll { def msg -> + msg.message?.code?.code in ['unknown_lints', 'renamed_and_removed_lints'] + } + .collect { def msg -> msg.message?.rendered?.toString() } + .findAll { String r -> r != null && !r.isEmpty() } + .unique() + if (!invalidLintRendered.isEmpty()) { + System.err.print(invalidLintRendered.join('')) + throw new GradleException('Unknown or renamed clippy lint in -PclippyLints') + } + if (exitValue != 0) { + List errorRendered = messages + .findAll { def msg -> msg.message?.level?.toString()?.startsWith('error') } + .collect { def msg -> msg.message?.rendered?.toString() } + .findAll { String r -> r != null && !r.isEmpty() } + .unique() + if (!errorRendered.isEmpty()) { + System.err.print(errorRendered.join('')) + } else if (!stderrText.isEmpty()) { + System.err.print(stderrText) + } + throw new GradleException("cargo clippy failed with exit code ${exitValue}") + } + List> hits = messages + .findAll { def msg -> msg.message?.code?.code } + .collect { def msg -> + def span = msg.message.spans.find { it.is_primary } ?: [:] + String file = span.file_name ?: '' + String at = span.line_start != null + ? (span.column_start != null + ? "${file}:${span.line_start}:${span.column_start}" + : "${file}:${span.line_start}") + : file + [ + lint: msg.message.code.code.toString().replaceFirst(/^clippy::/, ''), + at : at.toString(), + ] + } + .unique() + Map> counts = new LinkedHashMap<>() + lints.each { String lint -> + counts[lint] = hits.findAll { Map h -> h.lint == lint } + .collect { Map h -> h.at } + } + report.parentFile.mkdirs() + report.text = counts.collect { String lint, List at -> "${lint}: ${at.size()}" }.join('\n') + + '\n\n' + + counts.collect { String lint, List at -> (["## ${lint}"] + at.sort()).join('\n') }.join('\n\n') + + '\n' + counts.each { String lint, List at -> task.logger.lifecycle("${lint}: ${at.size()}") } + task.logger.lifecycle("Report: ${report}") + } + + private static void registerCleanTasks(RustSdkBuild build) { + build.cargoTask('cleanWorkspace', 'Build', + 'Remove compiled workspace crate artifacts while keeping dependency caches', + ['clean', '--workspace']).configure { Exec task -> + task.doLast { deleteBuildStamps(build) } } + build.cargoTask('cleanSdk', 'Build', 'Remove the cargo target directory', ['clean']).configure { Exec task -> + task.mustRunAfter('cleanWorkspace') + task.doLast { deleteBuildStamps(build) } + } + } + + private static void deleteBuildStamps(RustSdkBuild build) { + build.workspaceTestManifest.delete() + File cargoResults = build.buildFile('test-results/cargo') + cargoResults.listFiles()?.findAll { File f -> + f.name.startsWith('build-') && f.name.endsWith('.txt') + }?.each { File f -> f.delete() } } } diff --git a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustTestTasks.groovy b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustTestTasks.groovy index aa3cbb7d258b..feef6183b923 100644 --- a/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustTestTasks.groovy +++ b/buildSrc/src/main/groovy/org/apache/beam/gradle/rust/workspace/RustTestTasks.groovy @@ -17,28 +17,236 @@ */ package org.apache.beam.gradle.rust.workspace +import groovy.json.JsonException +import groovy.json.JsonSlurper +import groovy.transform.CompileDynamic import groovy.transform.CompileStatic +import groovy.transform.PackageScope import java.util.regex.Matcher import org.apache.beam.gradle.rust.RustSdkBuild +import org.gradle.api.Action import org.gradle.api.GradleException import org.gradle.api.Task +import org.gradle.api.file.RegularFileProperty import org.gradle.api.logging.Logger -import org.gradle.api.tasks.Exec +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.MapProperty +import org.gradle.api.provider.Property +import org.gradle.api.provider.Provider +import org.gradle.api.services.BuildService +import org.gradle.api.services.BuildServiceParameters +import org.gradle.api.services.BuildServiceSpec import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskProvider +import org.gradle.api.tasks.TaskState +import org.gradle.workers.WorkAction +import org.gradle.workers.WorkParameters /** - * The test tasks: one cacheable {@code test_} task for each crate, {@code test} and - * {@code testSummary}. + * The test tasks: {@code compileWorkspaceTests}, {@code testWorkspaceDoctests}, one cacheable + * {@code test_} task for each crate, {@code testSummary} and {@code test}. * *

The inputs of {@code test_} are the sources and tests of the crate, and the library - * sources of the workspace crates that it depends on. A change to a test of one crate does - * not run the tests of the crates that depend on it. + * sources of the workspace crates that it depends on. A change to a test of one crate does not + * run the tests of the crates that depend on it. */ @CompileStatic class RustTestTasks { - /** The test counts of one crate. */ + /** Limits how many crate test tasks execute in parallel. */ + abstract static class RustTestCoordinatorService implements BuildService {} + + /** Parameters for {@link CrateTestWorkAction}. */ + static interface CrateTestWorkParams extends WorkParameters { + Property getPkg() + Property getRustDir() + Property getCrateDir() + RegularFileProperty getManifestFile() + RegularFileProperty getStampFile() + Property getUseManifest() + Property getContinueOnFailure() + ListProperty getFeatureScope() + ListProperty getTestArgs() + MapProperty getEnvironment() + } + + /** Parameters for {@link DoctestWorkAction}. */ + static interface DoctestWorkParams extends WorkParameters { + Property getRustDir() + RegularFileProperty getStampFile() + ListProperty getCommand() + ListProperty getTestArgs() + MapProperty getEnvironment() + } + + /** Runs workspace doctests through Gradle's worker executor and writes their result and stamp. */ + abstract static class DoctestWorkAction implements WorkAction { + @Override + void execute() { + DoctestWorkParams p = parameters + File stamp = p.stampFile.get().asFile + File result = CrateTestWorkAction.resultFileOf(stamp) + result.delete() + List testArgs = p.testArgs.get() + + synchronized (CrateTestWorkAction.PRINT_LOCK) { + System.out.println('Running workspace doctests') + System.out.flush() + } + StringBuilder combinedOut = new StringBuilder() + int exit + synchronized (CrateTestWorkAction.CARGO_LOCK) { + exit = CrateTestWorkAction.runCapturing( + p.command.get(), p.rustDir.get(), p.environment.get(), combinedOut) + } + boolean failedExit = exit != 0 + Counts counts = countResults(combinedOut.toString(), false) + + synchronized (CrateTestWorkAction.PRINT_LOCK) { + if ((failedExit || requestsTestOutput(testArgs)) && combinedOut.length() > 0) { + System.out.print(combinedOut.toString()) + if (!combinedOut.toString().endsWith('\n')) { + System.out.println() + } + } + System.out.println("Total for workspace doctests: ${counts.passed} passed; " + + "${counts.failed} failed; ${counts.ignored} ignored; ${counts.filtered} filtered out") + System.out.flush() + } + + String line = "passed=${counts.passed} failed=${counts.failed} " + + "ignored=${counts.ignored} filtered=${counts.filtered}" + result.parentFile.mkdirs() + result.text = "${line} status=${failedExit ? 'FAILED' : 'EXECUTED'}\n" + if (failedExit) { + stamp.delete() + throw new GradleException('Workspace doctests failed') + } + RustSdkBuild.writeStamp(stamp, "${line}\n") + } + } + + /** Runs a crate's compiled test binaries (or {@code cargo test -p }) and writes its result and stamp. */ + abstract static class CrateTestWorkAction implements WorkAction { + @PackageScope static final Object CARGO_LOCK = new Object() + @PackageScope static final Object PRINT_LOCK = new Object() + + @PackageScope + static int runCapturing(List cmd, File dir, Map env, StringBuilder out) { + ProcessBuilder pb = new ProcessBuilder(cmd) + pb.directory(dir) + pb.redirectErrorStream(true) + pb.environment().putAll(env) + Process proc = pb.start() + try { + String text = proc.inputStream.getText('UTF-8') + int exit = proc.waitFor() + out.append(text) + return exit + } finally { + if (proc.alive) { + proc.destroyForcibly() + } + } + } + + @PackageScope + static File resultFileOf(File stamp) { + return new File(stamp.parentFile, "${stamp.name}.result") + } + + @Override + void execute() { + CrateTestWorkParams p = parameters + String pkg = p.pkg.get() + File rustDir = p.rustDir.get() + File crateDir = p.crateDir.get() + List testArgs = p.testArgs.get() + boolean cont = p.continueOnFailure.get() + List noFailFast = cont ? ['--no-fail-fast'] : new ArrayList() + Map cargoEnv = new LinkedHashMap<>(p.environment.get()) + Map binEnv = new LinkedHashMap<>(cargoEnv) + binEnv.put('CARGO_MANIFEST_DIR', crateDir.absolutePath) + + File stamp = p.stampFile.get().asFile + File result = resultFileOf(stamp) + result.delete() + synchronized (PRINT_LOCK) { + System.out.println("Running ${pkg}") + System.out.flush() + } + + StringBuilder combinedOut = new StringBuilder() + boolean failedExit = false + + if (p.useManifest.get()) { + List binaries = [] + File mf = p.manifestFile.get().asFile + mf.eachLine('UTF-8') { String line -> + if (!line.isEmpty()) { + String[] parts = line.split('\t', 3) + if (parts.length == 3 && parts[0] == pkg) { + binaries.add([parts[1], parts[2]] as String[]) + } + } + } + for (String[] entry : binaries) { + String targetName = entry[0] + String bin = entry[1] + if (combinedOut.length() > 0 && combinedOut.charAt(combinedOut.length() - 1) != (char) '\n') { + combinedOut.append('\n') + } + combinedOut.append("Running ${targetName} (${bin})\n") + int code = runCapturing([bin] + testArgs, crateDir, binEnv, combinedOut) + if (code != 0) { + if (combinedOut.length() > 0 && combinedOut.charAt(combinedOut.length() - 1) != (char) '\n') { + combinedOut.append('\n') + } + combinedOut.append("Test binary ${targetName} exited with code ${code}\n") + failedExit = true + if (!cont) { + break + } + } + } + } else { + List cargoCmd = ['cargo', 'test', '-p', pkg] + p.featureScope.get() + noFailFast + + (testArgs.isEmpty() ? new ArrayList() : ['--'] + testArgs) + int code + synchronized (CARGO_LOCK) { + code = runCapturing(cargoCmd, rustDir, cargoEnv, combinedOut) + } + if (code != 0) { + failedExit = true + } + } + + Counts counts = countResults(combinedOut.toString(), testArgs.isEmpty()) + synchronized (PRINT_LOCK) { + if ((failedExit || requestsTestOutput(testArgs)) && combinedOut.length() > 0) { + System.out.print(combinedOut.toString()) + if (!combinedOut.toString().endsWith('\n')) { + System.out.println() + } + } + System.out.println("Total for ${pkg}: ${counts.passed} passed; ${counts.failed} failed; " + + "${counts.ignored} ignored; ${counts.filtered} filtered out") + System.out.flush() + } + + String line = "passed=${counts.passed} failed=${counts.failed} " + + "ignored=${counts.ignored} filtered=${counts.filtered}" + result.parentFile.mkdirs() + result.text = "${line} status=${failedExit ? 'FAILED' : 'EXECUTED'}\n" + if (failedExit) { + stamp.delete() + throw new GradleException("Tests failed for ${pkg}") + } + RustSdkBuild.writeStamp(stamp, "${line}\n") + } + } + + /** The test counts of one crate or doctest suite. */ private static class Counts { int passed int failed @@ -47,73 +255,285 @@ class RustTestTasks { String status } - /** Writes to the console and keeps a copy, so that the task can count the results. */ - private static class TeeOutputStream extends OutputStream { - final ByteArrayOutputStream captured = new ByteArrayOutputStream() + /** Returns whether the test arguments ask libtest to print output even on passing runs. */ + private static boolean requestsTestOutput(List testArgs) { + return testArgs.any { String arg -> + arg in ['--nocapture', '--show-output', '--list', '--help', '-h'] + } + } - @Override - void write(int b) { - System.out.write(b) - captured.write(b) + static void register(RustSdkBuild build) { + String rawConcurrency = build.project.findProperty('testConcurrency')?.toString()?.trim() + int parsedConcurrency = 4 + if (rawConcurrency) { + try { + parsedConcurrency = Integer.parseInt(rawConcurrency) + } catch (NumberFormatException e) { + throw new GradleException( + "Invalid -PtestConcurrency='${rawConcurrency}': expected an integer", e) + } } + int testConcurrency = Math.max(1, parsedConcurrency) + Provider coordinator = build.project.gradle.sharedServices.registerIfAbsent( + "rustTestCoordinator_${build.project.path.replace(':', '_')}".toString(), + RustTestCoordinatorService.class, + { BuildServiceSpec spec -> + spec.maxParallelUsages.set(testConcurrency) + } as Action>) + String defaultThreads = testConcurrency > 1 + ? Math.max(2, (int) Math.ceil(Runtime.runtime.availableProcessors() / (double) testConcurrency)).toString() + : null - @Override - void write(byte[] b, int off, int len) { - System.out.write(b, off, len) - captured.write(b, off, len) + registerCompileWorkspaceTests(build) + File doctestStamp = doctestStampFile(build) + TaskProvider doctestTask = registerTestWorkspaceDoctests( + build, doctestStamp, coordinator, defaultThreads) + + Map stampFiles = new LinkedHashMap<>() + for (String pkg : build.workspace.topoOrder) { + File stamp = stampFile(build, pkg) + stampFiles[pkg] = stamp + build.testTasks[pkg] = registerCrateTest(build, pkg, stamp, coordinator, defaultThreads) } + registerSummary(build, stampFiles, doctestTask, doctestStamp, coordinator) + registerTest(build) + } - @Override - void flush() { - System.out.flush() + private static void registerCompileWorkspaceTests(RustSdkBuild build) { + File manifest = build.workspaceTestManifest + build.project.tasks.register('compileWorkspaceTests') { Task task -> + task.group = 'Verification' + task.description = 'Compile all workspace test binaries in one Cargo pass' + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix', 'clippy', 'clippyLintReport', + 'buildWorkspace') + task.inputs.property('beamSdkVersion', build.versions.sdkVersion) + task.inputs.property('beamReleaseVersion', build.versions.releaseVersion) + task.inputs.property('beamVersion', build.versions.beamVersion) + task.inputs.property('cargoTargetDir', build.cargoTargetDir().canonicalPath) + task.inputs.files(build.workspaceRootFiles).withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.libAndTestInputs(build.workspace.topoOrder)) + .withPathSensitivity(PathSensitivity.RELATIVE) + task.outputs.file(manifest) + task.outputs.upToDateWhen { + File targetDir = build.cargoTargetDir() + String targetPrefix = targetDir.canonicalPath + File.separator + targetDir.exists() && + manifest.isFile() && + manifest.readLines('UTF-8').every { String line -> + if (line.isEmpty()) { + return true + } + String[] parts = line.split('\t', 3) + if (parts.length != 3) { + return false + } + File exe = new File(parts[2]) + return exe.isFile() && exe.canonicalPath.startsWith(targetPrefix) + } + } + task.doLast { + ProcessBuilder pb = new ProcessBuilder( + ['cargo', 'test'] + build.workspaceScope + ['--no-run', '--message-format=json']) + pb.directory(build.rustDir) + pb.environment().putAll(build.versions.cargoEnv()) + Process proc = pb.start() + Thread errThread = Thread.start { + proc.errorStream.eachLine('UTF-8') { String line -> System.err.println(line) } + } + JsonSlurper slurper = new JsonSlurper() + List entries = [] + StringBuilder diagnostics = new StringBuilder() + boolean ok = false + try { + int exit + try { + proc.inputStream.eachLine('UTF-8') { String line -> + String trimmed = line.trim() + if (trimmed.startsWith('{')) { + try { + collectManifestMessage(slurper.parseText(trimmed), build.workspace.dirToPkg, entries, diagnostics) + } catch (JsonException ignored) { + // Skip non-JSON stdout lines from build scripts or proc-macros. + } + } + } + exit = proc.waitFor() + } finally { + if (proc.alive) { + proc.destroyForcibly() + } + errThread.join() + } + if (exit != 0) { + if (diagnostics.length() > 0) { + System.err.print(diagnostics.toString()) + } + throw new GradleException("cargo test --workspace --no-run failed with exit code ${exit}") + } + entries.sort() + manifest.parentFile.mkdirs() + manifest.setText(entries.isEmpty() ? '' : (entries.join('\n') + '\n'), 'UTF-8') + ok = true + } finally { + if (!ok) { + manifest.delete() + } + } + } } } - static void register(RustSdkBuild build) { - Map results = new LinkedHashMap<>() - Map stampFiles = new LinkedHashMap<>() + @CompileDynamic + private static void collectManifestMessage( + Object msg, Map dirToPkg, List entries, StringBuilder diagnostics) { + if (msg.reason == 'compiler-message' && msg.message?.rendered) { + if (msg.message.level?.toString()?.startsWith('error')) { + diagnostics.append(msg.message.rendered) + } + } else if (msg.reason == 'compiler-artifact' && msg.executable != null && msg.manifest_path) { + boolean isTestTarget = msg.target?.test == true && + (msg.profile?.test == true || (msg.target?.kind instanceof List && 'test' in msg.target.kind)) + if (isTestTarget) { + String pkg = dirToPkg[new File(msg.manifest_path.toString()).parentFile.canonicalPath] + if (pkg != null) { + entries.add("${pkg}\t${msg.target.name}\t${msg.executable}".toString()) + } + } + } + } - // Each test task runs after the previous one, so cargo processes do not wait on - // target/.cargo-lock, and base crates run before the crates that depend on them. - String previousTask = 'clippy' - for (String pkg : build.workspace.topoOrder) { - stampFiles[pkg] = stampFile(build, pkg) - build.testTasks[pkg] = registerCrateTest(build, pkg, previousTask, stampFiles[pkg], results) - previousTask = "test_${pkg}".toString() + private static File doctestStampFile(RustSdkBuild build) { + return build.buildFile( + "test-results/cargo/doctests/test-workspace${build.testArgs ? '-filtered' : ''}.txt") + } + + private static TaskProvider registerTestWorkspaceDoctests( + RustSdkBuild build, + File stampFile, + Provider coordinator, + String defaultThreads) { + List testArgs = build.testArgs + return build.project.tasks.register('testWorkspaceDoctests') { Task task -> + task.group = 'Verification' + task.description = 'Run all workspace Rust doctests in one Cargo pass' + task.usesService(coordinator) + task.dependsOn('compileWorkspaceTests') + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix', 'clippy', 'clippyLintReport', + 'buildWorkspace') + task.finalizedBy('testSummary') + + task.inputs.property('beamSdkVersion', build.versions.sdkVersion) + task.inputs.property('beamReleaseVersion', build.versions.releaseVersion) + task.inputs.property('beamVersion', build.versions.beamVersion) + task.inputs.property('benchmarkPackages', build.project.provider { + build.extension.benchmarkPackages.get().toList().sort() + }) + task.inputs.property('testArgs', testArgs) + task.inputs.files(build.workspaceRootFiles).withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) + task.inputs.files(build.project.provider { + Set closure = new LinkedHashSet<>() + build.defaultPackages().each { String pkg -> + closure.addAll(build.workspace.crateWorkspaceClosure[pkg] ?: Collections.emptySet()) + } + return build.libInputs(closure) + }).withPathSensitivity(PathSensitivity.RELATIVE) + + task.outputs.file(stampFile) + task.outputs.upToDateWhen { + testArgs.isEmpty() && (!stampFile.isFile() || readStamp(stampFile) != null) + } + task.outputs.cacheIf { testArgs.isEmpty() } + + task.doLast { + stampFile.delete() + CrateTestWorkAction.resultFileOf(stampFile).delete() + List benchmarkExcludes = build.extension.benchmarkPackages.get() + .toList() + .sort() + .collectMany { String pkg -> ['--exclude', pkg] } + List docCmd = ['cargo', 'test', '--doc'] + build.workspaceScope + benchmarkExcludes + + build.noFailFast + (testArgs.isEmpty() ? new ArrayList() : ['--'] + testArgs) + Map procEnv = baseTestEnv(build, defaultThreads) + build.workerExecutor.noIsolation().submit(DoctestWorkAction.class, { DoctestWorkParams p -> + p.rustDir.set(build.rustDir) + p.stampFile.set(stampFile) + p.command.set(docCmd) + p.testArgs.set(testArgs) + p.environment.set(procEnv) + } as Action) + } } - registerSummary(build, results, stampFiles) - registerTest(build) + } + + private static Map baseTestEnv(RustSdkBuild build, String defaultThreads) { + Map env = new LinkedHashMap<>(build.versions.cargoEnv()) + String javaHome = System.getenv('JAVA_HOME') ?: System.getProperty('java.home') + if (javaHome != null) { + env.put('JAVA_HOME', javaHome) + } + if (defaultThreads != null && System.getenv('RUST_TEST_THREADS') == null) { + env.put('RUST_TEST_THREADS', defaultThreads) + } + return env } private static File stampFile(RustSdkBuild build, String pkg) { - boolean ownFeatures = build.selectedPkg == pkg && build.onlyFeatures != null - String featureSuffix = ownFeatures - ? "-features-${build.onlyFeatures.replaceAll('[^a-zA-Z0-9_-]', '_')}" : '' + boolean manifestMode = build.selectedPkg == null + boolean narrowFeatures = build.selectedPkg == pkg && build.onlyFeatures != null + String featureKey = build.onlyFeatures != null && !build.onlyFeatures.trim().isEmpty() + ? build.onlyFeatures.replaceAll('[^a-zA-Z0-9_-]', '_') + : 'none' + String featureSuffix = narrowFeatures ? "-features-${featureKey}" : '' String filterSuffix = build.testArgs ? '-filtered' : '' - return build.buildFile("test-results/cargo/${pkg}/test${featureSuffix}${filterSuffix}.txt") + String modeSuffix = manifestMode ? '-workspace' : '' + return build.buildFile("test-results/cargo/${pkg}/test${modeSuffix}${featureSuffix}${filterSuffix}.txt") } - private static TaskProvider registerCrateTest( - RustSdkBuild build, String pkg, String runAfter, File stampFile, Map results) { + private static TaskProvider registerCrateTest( + RustSdkBuild build, + String pkg, + File stampFile, + Provider coordinator, + String defaultThreads) { List testArgs = build.testArgs - List featureScope = build.selectedPkg == pkg ? build.featureScope : new ArrayList() - Set closure = build.workspace.crateClosure[pkg] + boolean manifestMode = build.selectedPkg == null + boolean narrowFeatures = build.selectedPkg == pkg && build.onlyFeatures != null + String testMode = manifestMode ? 'manifest' : 'pkg' + List featureScope = narrowFeatures ? build.featureScope : new ArrayList() + Set closure = manifestMode + ? build.workspace.crateWorkspaceClosure[pkg] + : build.workspace.crateClosure[pkg] + String activeFeaturesInput = manifestMode + ? closure.toList().sort().collect { String dep -> + List active = (build.workspace.workspaceActiveFeatures[dep] ?: Collections.emptySet()) + .toList().sort() + return "${dep}=${active.join(',')}" + }.join(';') + : '' - return build.project.tasks.register("test_${pkg}".toString(), Exec) { Exec task -> + return build.project.tasks.register("test_${pkg}".toString()) { Task task -> task.group = 'Verification' - task.description = "Run cargo test for ${pkg}" - task.workingDir(build.rustDir) - task.commandLine(['cargo', 'test', '-p', pkg] + featureScope + build.noFailFast + - (testArgs ? ['--'] + testArgs : new ArrayList())) - task.ignoreExitValue = true + task.description = "Run tests for ${pkg}" + task.usesService(coordinator) task.finalizedBy('testSummary') - task.mustRunAfter(runAfter, 'buildWorkspace') + task.mustRunAfter('clean', 'cleanWorkspace', 'cleanSdk', 'fmt', 'clippyFix', 'clippy', 'clippyLintReport', + 'buildWorkspace') + if (manifestMode) { + task.dependsOn('compileWorkspaceTests') + } else { + task.mustRunAfter('compileWorkspaceTests') + } task.inputs.property('pkg', pkg) task.inputs.property('beamSdkVersion', build.versions.sdkVersion) task.inputs.property('beamReleaseVersion', build.versions.releaseVersion) + task.inputs.property('beamVersion', build.versions.beamVersion) task.inputs.property('featureScope', featureScope) + task.inputs.property('activeFeatures', activeFeaturesInput) task.inputs.property('testArgs', testArgs) + task.inputs.property('testMode', testMode) task.inputs.files(build.workspaceRootFiles).withPathSensitivity(PathSensitivity.RELATIVE) if ('apache-beam-model' in closure) { task.inputs.files(build.modelProtoDirs).withPathSensitivity(PathSensitivity.RELATIVE) @@ -124,27 +544,28 @@ class RustTestTasks { task.inputs.files(build.testInputFiles(pkg)).withPathSensitivity(PathSensitivity.RELATIVE) task.outputs.file(stampFile) - task.outputs.upToDateWhen { testArgs.isEmpty() && readStamp(stampFile) != null } + task.outputs.upToDateWhen { + testArgs.isEmpty() && (!stampFile.isFile() || readStamp(stampFile) != null) + } task.outputs.cacheIf { testArgs.isEmpty() } - TeeOutputStream output = new TeeOutputStream() - task.doFirst { - output.captured.reset() - task.standardOutput = output - } task.doLast { - Counts counts = countResults(output.captured.toString('UTF-8'), testArgs.isEmpty()) - task.logger.lifecycle("Total for ${pkg}: ${counts.passed} passed; ${counts.failed} failed; " + - "${counts.ignored} ignored; ${counts.filtered} filtered out") - int exitCode = task.executionResult.get().exitValue - counts.status = exitCode == 0 ? 'EXECUTED' : 'FAILED' - results[pkg] = counts - if (exitCode != 0) { - stampFile.delete() - task.executionResult.get().assertNormalExitValue() - } - RustSdkBuild.writeStamp(stampFile, "passed=${counts.passed} failed=${counts.failed} " + - "ignored=${counts.ignored} filtered=${counts.filtered}\n") + stampFile.delete() + CrateTestWorkAction.resultFileOf(stampFile).delete() + Map procEnv = baseTestEnv(build, defaultThreads) + boolean keepGoing = build.project.gradle.startParameter.continueOnFailure + build.workerExecutor.noIsolation().submit(CrateTestWorkAction.class, { CrateTestWorkParams p -> + p.pkg.set(pkg) + p.rustDir.set(build.rustDir) + p.crateDir.set(build.workspace.crateDir[pkg]) + p.manifestFile.set(build.workspaceTestManifest) + p.stampFile.set(stampFile) + p.useManifest.set(manifestMode) + p.continueOnFailure.set(keepGoing) + p.featureScope.set(featureScope) + p.testArgs.set(testArgs) + p.environment.set(procEnv) + } as Action) } } } @@ -184,36 +605,76 @@ class RustTestTasks { filtered: m.group(4) as int) } + private static Counts readResultFile(File resultFile) { + Counts counts = readStamp(resultFile) + if (counts == null) { + return null + } + Matcher status = (resultFile.text =~ /status=(\w+)/) + counts.status = status.find() ? status.group(1) : 'EXECUTED' + return counts + } + private static void registerSummary( - RustSdkBuild build, Map results, Map stampFiles) { + RustSdkBuild build, + Map stampFiles, + TaskProvider doctestTask, + File doctestStampFile, + Provider coordinator) { build.project.tasks.register('testSummary') { Task task -> task.group = 'Verification' task.description = 'Print the aggregated per-crate test summary' + task.usesService(coordinator) task.mustRunAfter(build.testTasks.values()) + task.mustRunAfter(doctestTask) task.doLast { - List packages = build.selectedPkg != null ? [build.selectedPkg] : build.defaultPackages() Map rows = new LinkedHashMap<>() - packages.each { String pkg -> - Counts counts = results[pkg] - if (counts == null && stampFiles[pkg] != null) { - counts = readStamp(stampFiles[pkg]) - if (counts != null) { - counts.status = 'UP-TO-DATE' - } - } + build.workspace.topoOrder.each { String pkg -> + Counts counts = collectTaskRow(build.testTasks[pkg], stampFiles[pkg]) if (counts != null) { rows[pkg] = counts } } + Counts docCounts = collectTaskRow(doctestTask, doctestStampFile) + if (docCounts != null) { + rows['workspace doctests'] = docCounts + } printSummary(task.logger, rows) } } } + private static Counts collectTaskRow(TaskProvider tp, File stamp) { + if (tp == null || stamp == null) { + return null + } + TaskState state = tp.get().state + if (state.upToDate) { + Counts cached = readStamp(stamp) + if (cached != null) { + cached.status = state.skipMessage ?: 'UP-TO-DATE' + return cached + } + return null + } + if (state.executed && !state.skipped) { + Counts result = readResultFile(CrateTestWorkAction.resultFileOf(stamp)) + if (result == null) { + return state.failure != null ? new Counts(status: 'FAILED') : null + } + if (state.failure != null) { + result.status = 'FAILED' + } + return result + } + return null + } + private static void printSummary(Logger logger, Map rows) { if (rows.isEmpty()) { return } + int crateCount = (int) rows.keySet().count { String k -> k != 'workspace doctests' } int nameWidth = Math.max(28, rows.keySet().collect { String pkg -> pkg.length() }.max() + 2) String separator = '-' * (nameWidth + 46) String rowFormat = "%-${nameWidth}s %8d %8d %9d %10d" @@ -225,8 +686,11 @@ class RustTestTasks { logger.lifecycle(String.format("${rowFormat} %s", pkg, c.passed, c.failed, c.ignored, c.filtered, c.status)) } logger.lifecycle(separator) + String totalLabel = crateCount > 0 + ? "Total (${crateCount} ${crateCount == 1 ? 'crate' : 'crates'})" + : 'Total (doctests)' logger.lifecycle(String.format(rowFormat, - "Total (${rows.size()} ${rows.size() == 1 ? 'crate' : 'crates'})".toString(), + totalLabel.toString(), rows.values().sum { Counts c -> c.passed }, rows.values().sum { Counts c -> c.failed }, rows.values().sum { Counts c -> c.ignored }, @@ -238,10 +702,11 @@ class RustTestTasks { build.project.tasks.register('test') { Task task -> task.group = 'Verification' task.description = 'Run tests (the workspace, or one crate with -Ppkg=; ' + - '-PtestArgs= after --; --continue runs every test binary)' + '-PtestArgs= after --; -PtestConcurrency= parallel crates; --continue runs every test binary)' task.finalizedBy('testSummary') String pkg = build.selectedPkg if (pkg == null) { + task.dependsOn('compileWorkspaceTests', 'testWorkspaceDoctests') task.dependsOn(build.project.provider { build.defaultPackages().collect { String name -> build.testTasks[name] } })