Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / build-logic / src / main / kotlin / RustNative.kt

RustNative.kt1183 lines · 59.8 KiBRaw
1import org.gradle.api.DefaultTask
2import org.gradle.api.GradleException
3import org.gradle.api.Project
4import org.gradle.api.artifacts.ProjectDependency
5import org.gradle.api.file.ConfigurableFileCollection
6import org.gradle.api.file.DirectoryProperty
7import org.gradle.api.provider.ListProperty
8import org.gradle.api.provider.Property
9import org.gradle.api.services.BuildService
10import org.gradle.api.services.BuildServiceParameters
11import org.gradle.api.tasks.Exec
12import org.gradle.api.tasks.Input
13import org.gradle.api.tasks.InputDirectory
14import org.gradle.api.tasks.InputFiles
15import org.gradle.api.tasks.OutputDirectory
16import org.gradle.api.tasks.PathSensitive
17import org.gradle.api.tasks.PathSensitivity
18import org.gradle.api.tasks.TaskAction
19import org.gradle.api.tasks.testing.Test
20import org.gradle.internal.os.OperatingSystem
21import org.gradle.kotlin.dsl.register
22import org.gradle.kotlin.dsl.withType
23import org.gradle.process.ExecOperations
24import java.io.File
25import java.util.Properties
26import javax.inject.Inject
27
28/**
29 * Shared build service that caps concurrent cargoBuild executions to 1.
30 * This prevents parallel invocations of `rustup toolchain install` triggered
31 * implicitly by cargo when rust-toolchain.toml pins 1.97.0, which is not
32 * concurrency-safe and produces "Directory not empty (os error 39)",
33 * "cargo not applicable", "failed to install component bin/rust-gdb" errors.
34 *
35 * `-Pmodernapps.cargoParallelism=N` raises the cap for builds whose toolchain is
36 * already installed (the release builder image pre-installs it, so no implicit
37 * rustup install can race). See [cargoParallelism].
38 */
39abstract class RustToolchainLock : BuildService<BuildServiceParameters.None>
40
41/**
42 * Maximum lines per Rust source file, mirroring the Kotlin `FileLength`
43 * rule (which cannot see Rust — Android lint only visits Kotlin/Java).
44 * Long files hide the same brace-imbalance breakage and grab-bag rot;
45 * splitting along module lines keeps each file reviewable.
46 *
47 * Enforced as a build failure, like `ToastUsage`: files already over the
48 * limit must be split before the owning module builds.
49 */
50const val RUST_FILE_LENGTH_LIMIT = 500
51
52/**
53 * Exemptions by filename: long by design, not by accretion — same rationale
54 * as `LENGTH_EXEMPT_FILES` in the Kotlin rule. Test fixtures and examples
55 * are long by nature; generated files are not hand-written.
56 */
57private val RUST_LENGTH_EXEMPT_FILES = setOf(
58 "route_diff.rs", // maps example harness with inline fixtures
59)
60
61private fun isRustLengthExempt(path: String): Boolean =
62 path.contains("/tests/") || path.contains("/test_fixtures/") ||
63 path.contains("/examples/") || path.contains("/generated/") ||
64 path.contains("/third_party/")
65
66/**
67 * How many cargoBuild tasks may run at once: `-Pmodernapps.cargoParallelism=N`
68 * (default 1, the historic fully serialized behaviour). The release build on a
69 * many-core box sets it to the number of Rust crate/ABI builds so the ~30 fat-LTO
70 * (codegen-units = 1, single-threaded) link steps overlap instead of queueing
71 * behind one another on the critical path. Only safe when the pinned toolchain is
72 * already installed (see [RustToolchainLock]). Read as a plain Int at configuration
73 * time, so it is configuration-cache safe.
74 */
75fun Project.cargoParallelism(): Int =
76 providers.gradleProperty("modernapps.cargoParallelism").orNull
77 ?.let { raw ->
78 raw.toIntOrNull()?.takeIf { it >= 1 }
79 ?: throw GradleException("Invalid -Pmodernapps.cargoParallelism=$raw: expected an integer >= 1.")
80 } ?: 1
81
82/**
83 * An Android ABI paired with the Rust target triple and the NDK clang-wrapper prefix
84 * used to cross-compile for it.
85 *
86 * @param clangPrefix deliberately separate from [triple]: for armeabi-v7a the NDK ships
87 * `armv7a-linux-androideabi<api>-clang` (note the `a`) while the Rust triple is
88 * `armv7-linux-androideabi`, so deriving one from the other silently misses the wrapper.
89 */
90data class RustAbi(val abiDir: String, val triple: String, val clangPrefix: String)
91
92/**
93 * Compiles GLSL entry points to `<name>.spv` with the NDK's glslc. Crates load the output with
94 * `include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/<name>.spv"))`,
95 * so standalone cargo (./check, ./test) needs this task to have run first.
96 */
97abstract class GlslcCompile @Inject constructor(
98 private val execOps: ExecOperations,
99) : DefaultTask() {
100 /** Whole shader dir, so `#include`d files invalidate the task too. */
101 @get:InputDirectory
102 @get:PathSensitive(PathSensitivity.RELATIVE)
103 abstract val shaderDir: DirectoryProperty
104
105 @get:InputFiles
106 @get:PathSensitive(PathSensitivity.RELATIVE)
107 abstract val sources: ConfigurableFileCollection
108
109 @get:Input
110 abstract val glslc: Property<String>
111
112 @get:Input
113 abstract val glslcArgs: ListProperty<String>
114
115 @get:OutputDirectory
116 abstract val outputDir: DirectoryProperty
117
118 @TaskAction
119 fun compile() {
120 val compiler = File(glslc.get())
121 if (!compiler.isFile) {
122 throw GradleException("glslc not found at $compiler. Install NDK $NDK_VERSION.")
123 }
124 val shaders = sources.files.sortedBy { it.name }
125 if (shaders.isEmpty()) throw GradleException("No shaders matched in ${shaderDir.get()}")
126 val out = outputDir.get().asFile
127 // Wipe first so a deleted shader can't leave a stale .spv behind for include_bytes!.
128 out.deleteRecursively()
129 out.mkdirs()
130 for (src in shaders) {
131 val spv = File(out, "${src.name}.spv")
132 execOps.exec {
133 commandLine(compiler.path, *glslcArgs.get().toTypedArray(), "-o", spv.path, src.path)
134 }
135 }
136 }
137}
138
139private val KNOWN_RUST_ABIS = listOf(
140 RustAbi(ABI_ARM64, "aarch64-linux-android", "aarch64-linux-android"),
141 RustAbi(ABI_ARMV7, "armv7-linux-androideabi", "armv7a-linux-androideabi"),
142 // Emulator-only; see [ABI_X86_64]. Never packaged by default.
143 RustAbi(ABI_X86_64, "x86_64-linux-android", "x86_64-linux-android"),
144)
145
146/**
147 * Host target triple for JVM unit tests that load Rust cdylibs via
148 * `System.loadLibrary`. Mirrors the pattern in
149 * `:library:everysync-core` (which predates this helper): GNU triple on
150 * Windows (MinGW — matches the installed toolchain; MSVC would need VS Build
151 * Tools), Apple triples on macOS, GNU triples on Linux. Resolved with plain
152 * JVM system properties at configuration time so the configuration cache is
153 * unaffected (a String, never a task or Project, crosses into task actions).
154 */
155fun hostRustTriple(): String {
156 val os = System.getProperty("os.name").lowercase()
157 val arch = System.getProperty("os.arch").lowercase()
158 val isArm = arch.contains("aarch64") || arch.startsWith("arm")
159 return when {
160 os.contains("win") -> if (isArm) "aarch64-pc-windows-gnullvm" else "x86_64-pc-windows-gnu"
161 os.contains("mac") -> if (isArm) "aarch64-apple-darwin" else "x86_64-apple-darwin"
162 else -> if (isArm) "aarch64-unknown-linux-gnu" else "x86_64-unknown-linux-gnu"
163 }
164}
165
166/** `lib<crate>.dylib` / `.so` / `<crate>.dll` for [hostRustTriple]. */
167fun hostRustLibFileName(crate: String): String = when {
168 System.getProperty("os.name").lowercase().contains("win") -> "$crate.dll"
169 System.getProperty("os.name").lowercase().contains("mac") -> "lib$crate.dylib"
170 else -> "lib$crate.so"
171}
172
173/**
174 * A `path = "..."` or workspace-inherited reference found in one manifest's
175 * dependency tables.
176 */
177private data class CargoDepRefs(val paths: List<String>, val workspaceNames: List<String>)
178
179private val cargoPathValue = Regex("""\bpath\s*=\s*("([^"]*)"|'([^']*)')""")
180private val cargoDottedWorkspace = Regex("""^([A-Za-z0-9_-]+)\.workspace\s*=\s*true\b""")
181private val cargoInlineWorkspace =
182 Regex("""^[A-Za-z0-9_-]+\s*=\s*\{[^}]*?\bworkspace\s*=\s*true\b""")
183private val cargoInlineWorkspaceName = Regex("""^([A-Za-z0-9_-]+)\s*=""")
184
185private fun stripTomlComment(line: String): String {
186 var inDouble = false
187 var inSingle = false
188 var i = 0
189 while (i < line.length) {
190 val c = line[i]
191 when {
192 c == '"' && !inSingle && (i == 0 || line[i - 1] != '\\') -> inDouble = !inDouble
193 c == '\'' && !inDouble -> inSingle = !inSingle
194 c == '#' && !inDouble && !inSingle -> return line.substring(0, i)
195 }
196 i++
197 }
198 return line
199}
200
201/**
202 * Dependency refs in a crate manifest: inline `path = "..."` entries plus
203 * `<name>.workspace = true` / `<name> = { workspace = true ... }` entries.
204 * Only dependency tables are scanned (`[dependencies]`,
205 * `[dev-dependencies]`, `[build-dependencies]`, `[target.*.dependencies]`,
206 * `[workspace.dependencies]`), so `[[bin]]`/`[lib]`/`[[example]]`
207 * `path = "src/..."` file entries never surface here — and the directory
208 * check in [findRustPathDepDirs] rejects them anyway.
209 */
210private fun parseCargoDepRefs(manifestText: String): CargoDepRefs {
211 val paths = mutableListOf<String>()
212 val workspaceNames = mutableListOf<String>()
213 var inDeps = false
214 for (rawLine in manifestText.lines()) {
215 val line = stripTomlComment(rawLine).trim()
216 if (line.startsWith("[")) {
217 inDeps = line.startsWith("[dependencies") ||
218 line.startsWith("[dev-dependencies") ||
219 line.startsWith("[build-dependencies") ||
220 line.startsWith("[target.") ||
221 line.replace(" ", "") == "[workspace.dependencies]"
222 continue
223 }
224 if (!inDeps || line.isEmpty()) continue
225 cargoPathValue.find(line)?.let {
226 paths += it.groupValues[2].ifEmpty { it.groupValues[3] }
227 }
228 cargoDottedWorkspace.find(line)?.let {
229 workspaceNames += it.groupValues[1]
230 }
231 if (cargoInlineWorkspace.containsMatchIn(line)) {
232 cargoInlineWorkspaceName.find(line)?.let {
233 workspaceNames += it.groupValues[1]
234 }
235 }
236 }
237 return CargoDepRefs(paths, workspaceNames)
238}
239
240/** `name = { path = "...", ... }` entries of root `[workspace.dependencies]`. */
241private fun parseWorkspacePathDeps(rootManifestText: String): Map<String, String> {
242 val out = LinkedHashMap<String, String>()
243 var inSection = false
244 for (rawLine in rootManifestText.lines()) {
245 val line = stripTomlComment(rawLine).trim()
246 if (line.startsWith("[")) {
247 inSection = line.replace(" ", "") == "[workspace.dependencies]"
248 continue
249 }
250 if (!inSection || line.isEmpty()) continue
251 if (cargoDottedWorkspace.containsMatchIn(line) ||
252 cargoInlineWorkspace.containsMatchIn(line)
253 ) {
254 // `name.workspace = true` re-export: no path of its own.
255 continue
256 }
257 val name = line.substringBefore("=").trim()
258 if (!name.matches(Regex("[A-Za-z0-9_-]+"))) continue
259 cargoPathValue.find(line)?.let {
260 out[name] = it.groupValues[2].ifEmpty { it.groupValues[3] }
261 }
262 }
263 return out
264}
265
266/**
267 * Reads a Cargo.toml through the file-contents provider so the configuration
268 * cache tracks it: editing any visited manifest invalidates configuration.
269 * Manifests outside the repo (defensive fallback) are read untracked.
270 */
271private fun Project.readCargoManifest(manifestFile: File): String {
272 val canonical = manifestFile.canonicalFile
273 fun relativeToBase(base: File): String? {
274 val prefix = base.canonicalPath.trimEnd(File.separatorChar) + File.separatorChar
275 return if (canonical.path.startsWith(prefix)) canonical.path.removePrefix(prefix) else null
276 }
277 relativeToBase(projectDir)?.let {
278 return providers.fileContents(layout.projectDirectory.file(it)).asText.get()
279 }
280 relativeToBase(rootProject.projectDir)?.let {
281 return providers.fileContents(rootProject.layout.projectDirectory.file(it)).asText.get()
282 }
283 return canonical.readText()
284}
285
286/** Stable per-crate input property name from the root-relative crate path. */
287private fun pathDepPropertyName(rootDir: File, depDir: File): String {
288 val rel = try {
289 depDir.relativeTo(rootDir).invariantSeparatorsPath
290 } catch (_: IllegalArgumentException) {
291 depDir.canonicalPath
292 }
293 return "pathDep_" + rel.replace(Regex("[^A-Za-z0-9]+"), "_")
294}
295
296/**
297 * Cross-crate path dependencies of the crate in [crateDir], e.g. euicc ->
298 * library/jni-http, camera/measure -> library/vision, maps/library:map ->
299 * library/tilecodec. Parsed generically from `path = "..."` entries (resolved
300 * relative to the crate dir) plus `<name>.workspace = true` entries (resolved
301 * against root `[workspace.dependencies]` paths), recursed with dedupe and a
302 * cycle guard. Only paths resolving to a directory containing Cargo.toml are
303 * accepted. Returns plain Files; callers build FileCollections from them so
304 * only those (never the Project) cross into task actions.
305 */
306private fun Project.findRustPathDepDirs(crateDir: File): List<File> {
307 val rootDir = rootProject.projectDir.canonicalFile
308 val workspacePaths =
309 parseWorkspacePathDeps(readCargoManifest(rootDir.resolve("Cargo.toml")))
310 val canonicalCrate = crateDir.canonicalFile
311 val visited = HashSet<File>()
312 visited += canonicalCrate
313 val found = mutableListOf<File>()
314 val queue = ArrayDeque<File>()
315 fun enqueue(base: File, rawPath: String) {
316 val resolved = File(base, rawPath).canonicalFile
317 if (!resolved.isDirectory || !resolved.resolve("Cargo.toml").isFile) return
318 if (visited.add(resolved)) {
319 found += resolved
320 queue += resolved
321 }
322 }
323 fun enqueueWorkspaceDep(name: String) {
324 workspacePaths[name]?.let { enqueue(rootDir, it) }
325 }
326 val seed = parseCargoDepRefs(readCargoManifest(canonicalCrate.resolve("Cargo.toml")))
327 seed.paths.forEach { enqueue(canonicalCrate, it) }
328 seed.workspaceNames.forEach(::enqueueWorkspaceDep)
329 while (queue.isNotEmpty()) {
330 val dir = queue.removeFirst()
331 val refs = parseCargoDepRefs(readCargoManifest(dir.resolve("Cargo.toml")))
332 refs.paths.forEach { enqueue(dir, it) }
333 refs.workspaceNames.forEach(::enqueueWorkspaceDep)
334 }
335 return found
336}
337
338/**
339 * Registers the per-ABI cargo cross-compile of a Rust cdylib into `build/rustJniLibs`,
340 * wired ahead of `preBuild`. This consolidates the ~80 lines of NDK-toolchain + cargo +
341 * reproducible-build boilerplate that used to be copy-pasted across every native module
342 * (pdf, camera, weather, passwords, e2ee-p2p). The caller still registers
343 * `build/rustJniLibs` as a jniLibs source dir in its own `android { }` block.
344 *
345 * Prereq: `rustup target add` for every triple built (see `rust-toolchain.toml`).
346 *
347 * @param crate cargo package lib name → produces `lib<crate>.so`
348 * @param remapLabel `--remap-path-prefix` label baked in for reproducible builds
349 * (defaults to [crate]).
350 * @param srcDir crate directory relative to the module (defaults to
351 * `src/main/rust`). Namespaces the per-ABI task names by
352 * [crate] so a module can build several crates.
353 * @param extraAbis ABIs to build in addition to [ABI_ARM64]. Opt-in per module so only
354 * the modules that need a second ABI pay for the extra cargo build;
355 * pass [ABI_ARMV7] for libraries consumed by an app that sets
356 * `nativeAbis { armv7 = true }`.
357 * @param features Cargo features to enable via `--features`. Resolved to a plain
358 * String list at configuration time so the build stays
359 * configuration-cache compatible (only the strings cross into
360 * the task action, never the Project).
361 * @param shaders Glob patterns under `$srcDir/shaders` to compile to SPIR-V into
362 * `build/spirv` ahead of the cargo build (see [GlslcCompile]). Empty
363 * means the crate has no Vulkan shaders. Only supported with the
364 * default [srcDir], since crates locate `build/spirv` relative to it.
365 * @param glslcArgs Extra glslc flags, e.g. `--target-env=vulkan1.1`, `-O`.
366 * @param hostTests Also build this crate for the host (`cargoBuildHost_<crate>`,
367 * see below) so JVM unit tests can `System.loadLibrary` it.
368 * Set to false for crates that cannot compile for host
369 * (Android-only deps like `ndk`/`oboe`, Vulkan/GLES paths
370 * with no host fallback): no host task is registered and
371 * [wireRustHostLibsForUnitTests] skips the crate cleanly
372 * instead of breaking unit tests that never load it.
373 */
374fun Project.rustNativeLib(
375 crate: String,
376 remapLabel: String = crate,
377 extraAbis: List<String> = emptyList(),
378 features: List<String> = emptyList(),
379 srcDir: String = "src/main/rust",
380 shaders: List<String> = emptyList(),
381 glslcArgs: List<String> = emptyList(),
382 hostTests: Boolean = true,
383) {
384 // Record that this project is a Rust module at all (even with
385 // hostTests = false, where no RustHostLibRef is registered below), so
386 // wireRustHostLibsForUnitTests can leave its Test tasks entirely alone
387 // instead of applying the non-Rust batching defaults.
388 rustNativeLibProjectPaths() += path
389 // Serialize cargoBuild across all Rust modules to avoid concurrent rustup installs
390 // (unless the build opts into parallel cargo, see cargoParallelism below).
391 val parallelCargo = cargoParallelism()
392 val rustLock = gradle.sharedServices.registerIfAbsent(
393 "rustToolchainLock",
394 RustToolchainLock::class.java
395 ) {
396 maxParallelUsages.set(parallelCargo)
397 }
398
399 val androidApiLevel = 31
400
401 // Resolved once per build, not once per native module: every
402 // rustNativeLib caller shares the stashed value via the Gradle extra
403 // cache. Plain String keeps the configuration cache happy.
404 fun resolveSdkDirOnce(): String {
405 val extra = gradle.extensions.extraProperties
406 if (extra.has("modernAppsSdkDir")) return extra.get("modernAppsSdkDir") as String
407 val dir = System.getenv("ANDROID_HOME")
408 ?: System.getenv("ANDROID_SDK_ROOT")
409 ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->
410 Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")
411 }
412 ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")
413 extra.set("modernAppsSdkDir", dir)
414 return dir
415 }
416
417 fun resolveSdkDir(): String = resolveSdkDirOnce()
418
419 val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"
420 val ndkRoot = "${resolveSdkDir()}/ndk/$NDK_VERSION"
421 val hostTag = when {
422 OperatingSystem.current().isMacOsX -> "darwin-x86_64"
423 OperatingSystem.current().isLinux -> "linux-x86_64"
424 OperatingSystem.current().isWindows -> "windows-x86_64"
425 else -> error("Unsupported host OS for NDK toolchain")
426 }
427 val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"
428 val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"
429
430 // arm64-v8a always; anything else is opt-in via extraAbis.
431 val rustAbis = (listOf(ABI_ARM64) + extraAbis).distinct().map { abiDir ->
432 KNOWN_RUST_ABIS.firstOrNull { it.abiDir == abiDir }
433 ?: error(
434 "rustNativeLib($crate): unknown ABI '$abiDir'. " +
435 "Known: ${KNOWN_RUST_ABIS.joinToString { it.abiDir }}"
436 )
437 }
438
439 // Config-cache compatible: snapshot to plain Strings at configuration time so
440 // only the strings (never the Project) cross into the task actions below.
441 val cargoFeatureArgs: List<String> =
442 if (features.isNotEmpty()) listOf("--features", features.joinToString(",")) else emptyList()
443
444 // Cargo profile chosen once at configuration time (plain String, config-cache
445 // safe). Explicit `-Pmodernapps.rustProfile=fast|release` wins; otherwise fail
446 // safe: `fast` only when every requested task is a dev/cargo task, else
447 // `release` so an ambiguous build never ships a fast-profile .so.
448 val devTaskPattern = Regex("(Dev|Debug)(?=[A-Z]|$)")
449 val profile: String = providers.gradleProperty("modernapps.rustProfile").orNull?.let { requested ->
450 if (requested != "fast" && requested != "release") {
451 throw GradleException(
452 "Invalid -Pmodernapps.rustProfile=$requested: expected 'fast' or 'release'."
453 )
454 }
455 requested
456 } ?: run {
457 val taskNames = gradle.startParameter.taskNames
458 if (taskNames.isNotEmpty() && taskNames.all { name ->
459 val lastSegment = name.substringAfterLast(':')
460 lastSegment.startsWith("cargo") || devTaskPattern.containsMatchIn(lastSegment)
461 }
462 ) "fast" else "release"
463 }
464
465 // Cross-crate path deps (euicc -> library/jni-http, camera -> library/vision,
466 // maps/library:map -> library/tilecodec, ...), parsed generically from
467 // Cargo.toml below. Computed once per crate — identical for every ABI — as
468 // plain Files; only the FileCollections built from them cross into tasks.
469 val pathDepDirs: List<File> = findRustPathDepDirs(file(srcDir))
470
471 val compileShaders = if (shaders.isEmpty()) null else {
472 require(srcDir == "src/main/rust") { "rustNativeLib($crate): shaders need the default srcDir" }
473 val glslcExe = if (OperatingSystem.current().isWindows) "glslc.exe" else "glslc"
474 tasks.register<GlslcCompile>("compileShaders") {
475 description = "Compiles $crate's GLSL to SPIR-V."
476 shaderDir.set(file("$srcDir/shaders"))
477 sources.from(fileTree("$srcDir/shaders") { include(shaders) })
478 glslc.set("$ndkRoot/shader-tools/$hostTag/$glslcExe")
479 this.glslcArgs.set(glslcArgs)
480 outputDir.set(layout.buildDirectory.dir("spirv"))
481 }
482 }
483
484 val perAbi = rustAbis.map { abi ->
485 val (abiDir, triple) = abi
486 tasks.register<Exec>("cargoBuild_${crate}_${abiDir.replace('-', '_')}") {
487 usesService(rustLock)
488 description = "Cross-compiles lib$crate for $abiDir."
489 workingDir = file(srcDir)
490
491 // Windows hosts use the .cmd clang wrappers and .exe tool suffixes; Unix hosts none.
492 val isWindows = OperatingSystem.current().isWindows
493 val exeExt = if (isWindows) ".exe" else ""
494 val clangExt = if (isWindows) ".cmd" else ""
495 val clang = "$ndkBin/${abi.clangPrefix}$androidApiLevel-clang$clangExt"
496 val clangpp = "$ndkBin/${abi.clangPrefix}$androidApiLevel-clang++$clangExt"
497 val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"
498 // Per-crate target (may exist from older isolated builds) and workspace root target
499 // (current scheme since Cargo.toml workspace unified to root).
500 val perCrateSoOut = file("$srcDir/target/$triple/$profile/lib$crate.so")
501 val workspaceSoOut = rootProject.file("target/$triple/$profile/lib$crate.so")
502 // Parallel cargo: cargo locks its whole build dir, so concurrent builds
503 // sharing the workspace target/ would still run one at a time. Give each
504 // crate+ABI its own target dir instead. No sharing is lost: every crate
505 // passes its own --remap-path-prefix RUSTFLAGS, so cargo rebuilds the
506 // shared deps per crate in the workspace target/ anyway. The target dir
507 // path is not baked into the .so (verified byte-identical vs the shared
508 // target/ on the v2.6.11b release build).
509 val isolatedTargetDir: File? = if (parallelCargo > 1) {
510 rootProject.file("target/isolated/$crate-$abiDir")
511 } else {
512 null
513 }
514 val isolatedSoOut = isolatedTargetDir?.let { File(it, "$triple/$profile/lib$crate.so") }
515 val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/lib$crate.so").get().asFile
516 val targetRustflags = "-C link-arg=-Wl,-z,max-page-size=16384"
517
518 // Cacheable + relocatable: every input is RELATIVE-sensitive with a
519 // distinct property name, and toolchain facts the env doesn't cover
520 // (Exec treats environment/workingDir as @Internal, so env vars are
521 // NOT in the cache key) are explicit input properties. A fresh
522 // worktree at a different absolute path then restores FROM-CACHE.
523 outputs.cacheIf("Rust cdylib build is hermetic given the declared inputs") { true }
524
525 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
526 .withPropertyName("crateSrc")
527 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
528 .withPropertyName("crateManifest")
529 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
530 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
531 .withPropertyName("buildRs")
532 }
533 // The crate include_bytes!s build/spirv, so a shader edit must re-run cargo;
534 // otherwise the task stays up to date and the old SPIR-V silently ships.
535 compileShaders?.let {
536 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
537 .withPropertyName("spirv")
538 }
539 // `:library:ml`'s build.rs also compiles `schema/maml2.fbs` to Rust via
540 // flatc and `include!`s the result, so a schema edit changes the .so too.
541 // Same staleness hazard as shaders above: without this the task stays up
542 // to date and the old bindings ship.
543 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
544 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
545 .withPropertyName("schema")
546 }
547 // Whole-crate safety net: track every source under src/main/rust so ANY
548 // rust change invalidates cargoBuild - crucially vendored dependency
549 // crates under vendor/, which
550 // the path-specific inputs above do NOT cover. Before this, editing a
551 // vendored crate left the task UP-TO-DATE and shipped a stale .so. Exclude
552 // target/ because cargo writes this task's own .so there; folding build
553 // output back in as an input means the task can never be up to date. The
554 // FileTree is a FileCollection resolved at configuration time, so only the
555 // file set (never the Project) crosses into the task action.
556 inputs.files(fileTree(srcDir) { exclude("target/**") })
557 .withPathSensitivity(PathSensitivity.RELATIVE)
558 .withPropertyName("rustCrateTree")
559 // Cross-crate path deps (euicc -> jni-http, camera -> vision,
560 // maps -> tilecodec, ...): an edit there must rebuild this .so.
561 // Parsed generically from Cargo.toml `path =` + `workspace = true`
562 // entries (see findRustPathDepDirs), one input tree per dep crate.
563 for (depDir in pathDepDirs) {
564 val relDep = depDir.relativeTo(rootProject.projectDir)
565 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
566 .withPathSensitivity(PathSensitivity.RELATIVE)
567 .withPropertyName(pathDepPropertyName(rootProject.projectDir, depDir))
568 }
569 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
570 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
571 .withPropertyName("workspaceManifest")
572 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
573 .withPropertyName("workspaceLock")
574 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
575 .withPropertyName("rustToolchain")
576 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
577 // jni is a crates.io dependency now, so Cargo.lock above covers it.
578 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
579 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiSrc")
580 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
581 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiManifest")
582 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
583 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiBuildRs")
584 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
585 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiC")
586 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
587 inputs.dir(rootProject.file("third_party/betocore"))
588 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("betocore")
589 // Toolchain facts that shape the .so bytes but live in env/workingDir
590 // (both @Internal on Exec), so they need explicit input properties.
591 inputs.property("ndkVersion", NDK_VERSION)
592 inputs.property("hostTag", hostTag)
593 inputs.property("androidApiLevel", androidApiLevel)
594 inputs.property("targetRustflags", targetRustflags)
595 outputs.file(destSo)
596
597 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
598 val rustSrc = file(srcDir).absolutePath
599
600 val pathSep = if (isWindows) ";" else ":"
601 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
602 // A non-rustup rustc earlier on PATH (e.g. Homebrew's) has no
603 // aarch64-linux-android std, so cargo fails with "can't find crate for core".
604 // Pin the rustup shim explicitly.
605 environment("RUSTC", "$cargoBin/rustc$exeExt")
606 // The per-API NDK clang wrapper bakes in --target and the sysroot.
607 environment("CC", clang)
608 environment("CXX", clangpp)
609 environment("AR", "$ndkBin/llvm-ar$exeExt")
610 environment("SYSROOT", ndkSysroot)
611 environment(linkerVar, clang)
612 // Android 15 requires 16 KB page alignment on arm64 (Play blocks
613 // 4 KB .so files). Target-scoped so host build-script links on
614 // MSVC are unaffected. See analysis/plan-16kb-page-size.md.
615 val rustflagsVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_RUSTFLAGS"
616 environment(rustflagsVar, targetRustflags)
617 // Force the system clang for host-side C on Unix; on Windows let cc locate MinGW gcc.
618 if (!isWindows) environment("HOST_CC", "/usr/bin/clang")
619 // Pre-generated bindings (armv8-only): weather's om-file-format-sys no longer uses bindgen
620 // (bindings_android.rs/host checked in), so BINDGEN_EXTRA_CLANG_ARGS is no longer needed for build.
621 // Kept as comment for documentation if future C sys crates added.
622 // environment("BINDGEN_EXTRA_CLANG_ARGS", "--target=$triple$androidApiLevel --sysroot=$ndkSysroot")
623 // Reproducible builds: remap $HOME-specific paths (cargo registry + crate
624 // dir) to fixed constants so different machines produce identical .so bytes.
625 environment(
626 "RUSTFLAGS",
627 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",
628 )
629 environment("CFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
630 environment("CXXFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
631 environment("CPPFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel -Wdate-time -Werror=date-time")
632 environment("ZERO_AR_DATE", "1")
633 // Reproducible builds: respect SOURCE_DATE_EPOCH if set (exported by the release build)
634 // https://reproducible-builds.org/docs/source-date-epoch/
635 System.getenv("SOURCE_DATE_EPOCH")?.takeIf { it.isNotBlank() }?.let {
636 environment("SOURCE_DATE_EPOCH", it)
637 }
638 environment("CARGO_INCREMENTAL", "0")
639 isolatedTargetDir?.let { environment("CARGO_TARGET_DIR", it.absolutePath) }
640
641 commandLine(
642 "$cargoBin/cargo$exeExt",
643 "build",
644 "--locked",
645 "--profile",
646 profile,
647 "--target",
648 triple,
649 *cargoFeatureArgs.toTypedArray(),
650 )
651
652 doLast {
653 destSo.parentFile.mkdirs()
654 val src = when {
655 isolatedSoOut != null -> isolatedSoOut.takeIf { it.exists() }
656 ?: error("cargo produced no ${isolatedSoOut.path} for $crate")
657 perCrateSoOut.exists() -> perCrateSoOut
658 workspaceSoOut.exists() -> workspaceSoOut
659 else -> error("Neither per-crate ${perCrateSoOut.path} nor workspace ${workspaceSoOut.path} exists for $crate")
660 }
661 src.copyTo(destSo, overwrite = true)
662 }
663 }
664 }
665
666 val cargoNdkBuild = tasks.register("cargoNdkBuild_$crate") {
667 description = "Builds lib$crate.so for all Android ABIs."
668 dependsOn(perAbi)
669 }
670 // Keep the historic aggregate name for the default crate dir so existing
671 // invocations (`./gradlew :mod:cargoNdkBuild`) keep working.
672 if (srcDir == "src/main/rust") {
673 tasks.register("cargoNdkBuild") {
674 description = "Builds lib$crate.so for all Android ABIs."
675 dependsOn(cargoNdkBuild)
676 }
677 }
678 // Host cdylib for JVM unit tests (testDevUnitTest / testDevUnitTest):
679 // `cargo build --locked --target <hostTriple>` with the same profile,
680 // features, env (RUSTC pin, PATH, RUSTFLAGS remap, CARGO_INCREMENTAL=0),
681 // toolchain lock, inputs/outputs, and caching as the per-ABI tasks above —
682 // but WITHOUT any Android linker/NDK env (no CC/CXX/AR/SYSROOT, no
683 // per-target LINKER/RUSTFLAGS, no 16 KB page-size link arg: that flag
684 // would break the host link). The output (`lib<crate>.dylib/.so/.dll`)
685 // is installed into `build/rustHostLibs`, which nothing packages — APK/AAB
686 // assembly reads only `build/rustJniLibs`, so Android outputs are
687 // unchanged. Lazy by construction: nothing depends on this task except
688 // unit Test tasks (see wireRustHostLibsForUnitTests), so assemble/install
689 // never build it. With hostTests = false nothing is registered and
690 // dependents' tests never notice the crate.
691 val hostTriple: String = hostRustTriple()
692 val hostTaskName = "cargoBuildHost_$crate"
693 if (hostTests) {
694 val cargoBuildHost = tasks.register<Exec>(hostTaskName) {
695 usesService(rustLock)
696 description = "Builds lib$crate for the host (JVM unit tests)."
697 workingDir = file(srcDir)
698
699 val isWindowsHost = OperatingSystem.current().isWindows
700 val exeExt = if (isWindowsHost) ".exe" else ""
701 val hostLibName = hostRustLibFileName(crate)
702 // Per-crate target (may exist from older isolated builds) and workspace root target
703 // (current scheme since Cargo.toml workspace unified to root).
704 val perCrateHostOut = file("$srcDir/target/$hostTriple/$profile/$hostLibName")
705 val workspaceHostOut = rootProject.file("target/$hostTriple/$profile/$hostLibName")
706 val destHostLib = layout.buildDirectory.file("rustHostLibs/$hostLibName").get().asFile
707
708 // Same cacheable + relocatable shape as the per-ABI tasks: every
709 // input is RELATIVE-sensitive with a distinct (host-prefixed)
710 // property name, and host-toolchain facts the env doesn't cover
711 // are explicit input properties.
712 outputs.cacheIf("Rust cdylib host build is hermetic given the declared inputs") { true }
713
714 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
715 .withPropertyName("hostCrateSrc")
716 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
717 .withPropertyName("hostCrateManifest")
718 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
719 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
720 .withPropertyName("hostBuildRs")
721 }
722 // Same SPIR-V staleness hazard as the ABI tasks: the crate
723 // include_bytes!s build/spirv, so a shader edit must re-run cargo.
724 compileShaders?.let {
725 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
726 .withPropertyName("hostSpirv")
727 }
728 // Same flatc-bindings staleness hazard as the ABI tasks (see above).
729 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
730 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
731 .withPropertyName("hostSchema")
732 }
733 inputs.files(fileTree(srcDir) { exclude("target/**") })
734 .withPathSensitivity(PathSensitivity.RELATIVE)
735 .withPropertyName("hostRustCrateTree")
736 for (depDir in pathDepDirs) {
737 val relDep = depDir.relativeTo(rootProject.projectDir)
738 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
739 .withPathSensitivity(PathSensitivity.RELATIVE)
740 .withPropertyName("host_" + pathDepPropertyName(rootProject.projectDir, depDir))
741 }
742 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
743 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
744 .withPropertyName("hostWorkspaceManifest")
745 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
746 .withPropertyName("hostWorkspaceLock")
747 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
748 .withPropertyName("hostRustToolchain")
749 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
750 // jni is a crates.io dependency now, so Cargo.lock above covers it.
751 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
752 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiSrc")
753 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
754 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiManifest")
755 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
756 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiBuildRs")
757 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
758 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiC")
759 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
760 inputs.dir(rootProject.file("third_party/betocore"))
761 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostBetocore")
762 // Host-toolchain facts that shape the lib bytes but live in env/workingDir
763 // (both @Internal on Exec), so they need an explicit input property.
764 // Deliberately NOT the NDK props: the host link must not see them.
765 inputs.property("hostTriple", hostTriple)
766 outputs.file(destHostLib)
767
768 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
769 val rustSrc = file(srcDir).absolutePath
770
771 val pathSep = if (isWindowsHost) ";" else ":"
772 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
773 // Same non-rustup-rustc hazard as the ABI tasks: pin the shim.
774 environment("RUSTC", "$cargoBin/rustc$exeExt")
775 // Reproducible builds: same $HOME remap as the ABI tasks.
776 environment(
777 "RUSTFLAGS",
778 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",
779 )
780 environment("CARGO_INCREMENTAL", "0")
781
782 commandLine(
783 "$cargoBin/cargo$exeExt",
784 "build",
785 "--locked",
786 "--profile",
787 profile,
788 "--target",
789 hostTriple,
790 *cargoFeatureArgs.toTypedArray(),
791 )
792
793 doLast {
794 destHostLib.parentFile.mkdirs()
795 val src = when {
796 perCrateHostOut.exists() -> perCrateHostOut
797 workspaceHostOut.exists() -> workspaceHostOut
798 else -> error("Neither per-crate ${perCrateHostOut.path} nor workspace ${workspaceHostOut.path} exists for $crate")
799 }
800 src.copyTo(destHostLib, overwrite = true)
801 }
802 }
803 // Same historic-aggregate convenience as cargoNdkBuild for the default
804 // crate dir (`./gradlew :mod:cargoBuildHost`); per-crate task names stay
805 // unique for multi-crate modules (communicate's rust-mls second crate).
806 if (srcDir == "src/main/rust") {
807 tasks.register("cargoBuildHost") {
808 description = "Builds lib$crate for the host (JVM unit tests)."
809 dependsOn(cargoBuildHost)
810 }
811 }
812 // Recorded for wireRustHostLibsForUnitTests: plain strings only, so the
813 // configuration cache never sees a Project.
814 rustHostLibRefs().getOrPut(path) { mutableListOf() } += RustHostLibRef(
815 projectPath = path,
816 taskName = hostTaskName,
817 libDir = layout.buildDirectory.dir("rustHostLibs").get().asFile.absolutePath,
818 )
819 } else {
820 logger.warn("rustNativeLib($crate): hostTests = false — JVM unit tests cannot load this crate.")
821 }
822 // Rust file-length gate: fails the build on any *.rs over
823 // RUST_FILE_LENGTH_LIMIT lines, like the Kotlin FileLength rule (which
824 // cannot see Rust). Configuration-cache compatible: plain path strings
825 // cross the configuration boundary, never the Project object.
826 val rustSrcPath: String = file("$srcDir/src").absolutePath
827 val rustProjPath: String = projectDir.absolutePath
828 val lengthTaskName = if (srcDir == "src/main/rust") "rustFileLength" else "rustFileLength_$crate"
829 val rustFileLength = tasks.register(lengthTaskName) {
830 description = "Fails on Rust files over $RUST_FILE_LENGTH_LIMIT lines."
831 inputs.dir(rustSrcPath)
832 doLast {
833 val srcDir = java.io.File(rustSrcPath)
834 val projDir = java.io.File(rustProjPath)
835 val over = srcDir.walkTopDown()
836 .filter { it.isFile && it.extension == "rs" }
837 .map { it to it.readLines().size }
838 .filter { (f, n) ->
839 n > RUST_FILE_LENGTH_LIMIT &&
840 f.name !in RUST_LENGTH_EXEMPT_FILES &&
841 !isRustLengthExempt(f.path)
842 }
843 .toList()
844 if (over.isNotEmpty()) {
845 val detail = over.joinToString("\n") { (f, n) ->
846 " $n ${f.relativeTo(projDir)}"
847 }
848 throw org.gradle.api.GradleException(
849 "Rust files exceed $RUST_FILE_LENGTH_LIMIT lines (split along module lines):\n$detail"
850 )
851 }
852 }
853 }
854 tasks.matching { it.name == "preBuild" }.configureEach {
855 dependsOn(cargoNdkBuild)
856 dependsOn(rustFileLength)
857 }
858}
859
860/**
861 * One host-testable crate registered by [rustNativeLib]: the owning project's
862 * path, the host build task name, and the `build/rustHostLibs` dir. Plain
863 * strings only, so the configuration cache never sees a Project.
864 */
865data class RustHostLibRef(
866 val projectPath: String,
867 val taskName: String,
868 val libDir: String,
869)
870
871/**
872 * Project paths of every module that called [rustNativeLib], host-testable
873 * or not. Plain Strings in the root extra properties, mirroring
874 * [rustHostLibRefs], so the configuration cache never sees a Project.
875 */
876private fun Project.rustNativeLibProjectPaths(): MutableSet<String> {
877 val extra = rootProject.extensions.extraProperties
878 @Suppress("UNCHECKED_CAST")
879 return if (extra.has("rustNativeLibProjectPaths")) {
880 extra.get("rustNativeLibProjectPaths") as MutableSet<String>
881 } else {
882 mutableSetOf<String>().also { extra.set("rustNativeLibProjectPaths", it) }
883 }
884}
885
886/** Shared `projectPath -> host crates` registry (see [RustHostLibRef]). */
887private fun Project.rustHostLibRefs(): MutableMap<String, MutableList<RustHostLibRef>> {
888 val extra = rootProject.extensions.extraProperties
889 @Suppress("UNCHECKED_CAST")
890 return if (extra.has("rustHostLibRefs")) {
891 extra.get("rustHostLibRefs") as MutableMap<String, MutableList<RustHostLibRef>>
892 } else {
893 mutableMapOf<String, MutableList<RustHostLibRef>>().also { extra.set("rustHostLibRefs", it) }
894 }
895}
896
897/**
898 * Per-module opt-in for splitting native-loading unit tests out of the main
899 * unit-test task (see [wireRustHostLibsForUnitTests]).
900 *
901 * A test class belongs in the native split when executing it can actually
902 * `System.loadLibrary` a Rust cdylib — directly, or through the module's
903 * `<Feature>Native` wrapper / a facade over it (e.g. appstore's
904 * `Signify.verify` -> `SignifyNative`). Classes that merely reference a
905 * repository whose native path is stubbed out in the test do NOT load the
906 * library and stay in the main task.
907 */
908abstract class RustNativeTestsExtension {
909 /**
910 * Fully-qualified names of test classes that load a Rust native library.
911 * Each name also matches its nested classes. Naming a class here (or
912 * adding [nativePatterns]) enables the split for the module.
913 */
914 abstract val nativeClasses: ListProperty<String>
915
916 /**
917 * Extra class-file include patterns for native-loading tests, in Gradle
918 * [Test] include syntax (glob patterns over class-file paths). Added to
919 * the built-in conventions in [DEFAULT_NATIVE_TEST_PATTERNS].
920 */
921 abstract val nativePatterns: ListProperty<String>
922
923 /**
924 * Fully-qualified names of test classes that must keep one-JVM-per-class
925 * for a non-JNI reason: they pollute a shared JVM (leaked
926 * `viewModelScope` collectors on the process-wide DataStores, persisted
927 * DataStore files, process-wide flows) or depend on that state being
928 * fresh. Each name also matches its nested classes. These classes join
929 * the same per-class companion task as [nativeClasses]; the companion
930 * is a quarantine, whatever the reason a class needs its own JVM.
931 */
932 abstract val isolatedClasses: ListProperty<String>
933
934 /**
935 * Enables the split even with no explicit classes/patterns, relying only
936 * on the built-in naming/package conventions. Defaults to false: modules
937 * that have not audited which classes load a native library keep the
938 * historic one-JVM-per-class behaviour for every test.
939 */
940 abstract val split: Property<Boolean>
941}
942
943/** DSL entry point for [RustNativeTestsExtension], e.g. in a module build file. */
944fun Project.rustNativeTests(configure: RustNativeTestsExtension.() -> Unit) {
945 rustNativeTestsExtension().configure()
946}
947
948private fun Project.rustNativeTestsExtension(): RustNativeTestsExtension =
949 extensions.findByType(RustNativeTestsExtension::class.java)
950 ?: extensions.create("rustNativeTests", RustNativeTestsExtension::class.java)
951
952/** Suffix of the per-class-fork companion task of a unit-test task (`testDevUnitTest` -> `testDevUnitTestNative`). */
953const val NATIVE_TEST_TASK_SUFFIX = "Native"
954
955/**
956 * Built-in conventions for native-loading test classes, as class-file
957 * patterns: a test type named `*Native*Test(s)` in any package, or any test
958 * type under a `native` package segment. Deliberately narrow — a class that
959 * matches but never actually loads a library only costs itself a dedicated
960 * JVM, while the explicit [RustNativeTestsExtension.nativeClasses] list is
961 * the precise mechanism for loaders that follow neither convention
962 * (appstore's `FingerprintNormalizeTest` reaches `SignifyNative` through
963 * `Signify.verify`).
964 */
965val DEFAULT_NATIVE_TEST_PATTERNS: List<String> = listOf(
966 "**/*NativeTest.class",
967 "**/*NativeTest\$*.class",
968 "**/*NativeTests.class",
969 "**/*NativeTests\$*.class",
970 "**/native/**Test.class",
971 "**/native/**Test\$*.class",
972 "**/native/**Tests.class",
973 "**/native/**Tests\$*.class",
974)
975
976/**
977 * Wires every unit [Test] task (testDevUnitTest, testDebugUnitTest, ...) so
978 * `System.loadLibrary` finds Rust cdylibs on the host JVM: each Test task
979 * depends on the host build tasks of this module and of every project it
980 * transitively depends on that registered one via [rustNativeLib]
981 * (e.g. `:office` also picks up `:library:e2ee-p2p`'s `e2ee_pqc`), and
982 * `java.library.path` gains each of their `build/rustHostLibs` dirs.
983 *
984 * The existing value is appended to, never clobbered: AGP's own
985 * `src/test/jniLibs` dirs (which AGP merges into the same property) survive
986 * regardless of ordering, because both sides merge. Crates opted out with
987 * `hostTests = false` register no task and are skipped cleanly.
988 *
989 * Laziness: the host tasks are reachable only through these `dependsOn`
990 * edges, so assemble/install never build them. Configuration-cache safe:
991 * `evaluationDependsOn` pulls transitive deps through evaluation before any
992 * state is read, and only plain strings (task paths, dir paths) cross into
993 * task configuration — never a Project.
994 *
995 * Dual role: this is also where the app/library conventions get their
996 * non-Rust Test batching. When neither this project nor any project dep
997 * registered a host lib (and none called [rustNativeLib] at all), the
998 * afterEvaluate below configures every Test task with `forkEvery = 20`,
999 * `maxParallelForks = (cores / 2).coerceIn(1, 3)` and `maxHeapSize = "1g"`.
1000 * When a Rust module is involved it returns without touching the task —
1001 * the `forkEvery = 1` wiring below (and the rustNativeTests split) owns it.
1002 */
1003fun Project.wireRustHostLibsForUnitTests() {
1004 // Created here, while the convention plugin is being applied, so the
1005 // module's own build file (evaluated afterwards) can configure it via
1006 // `rustNativeTests { ... }`. Read only in afterEvaluate below, when the
1007 // module's values are final.
1008 rustNativeTestsExtension().split.convention(false)
1009 // Deferred to afterEvaluate: the module's own `dependencies {}` block runs
1010 // after the convention plugin, so the project-dep graph is only complete
1011 // then. Task wiring uses configureEach, which covers Test tasks whether
1012 // AGP already created them or creates them later.
1013 afterEvaluate {
1014 val self = this@wireRustHostLibsForUnitTests
1015 val ordered = mutableListOf<String>()
1016 val seen = HashSet<String>()
1017 seen += self.path
1018 val queue = ArrayDeque<String>()
1019 fun enqueueDepsOf(p: Project) {
1020 p.configurations.forEach { cfg ->
1021 cfg.dependencies.filterIsInstance<ProjectDependency>().forEach { dep ->
1022 val depPath = dep.path
1023 if (seen.add(depPath)) {
1024 queue += depPath
1025 ordered += depPath
1026 }
1027 }
1028 }
1029 }
1030 enqueueDepsOf(self)
1031 while (queue.isNotEmpty()) {
1032 val depPath = queue.removeFirst()
1033 self.evaluationDependsOn(depPath)
1034 enqueueDepsOf(self.project(depPath))
1035 }
1036 val refs = (listOf(self.path) + ordered).flatMap { rustHostLibRefs()[it].orEmpty() }
1037 if (refs.isEmpty()) {
1038 // Non-Rust modules (neither this project nor any project dep
1039 // called rustNativeLib): RustNative does not control these Test
1040 // tasks, so give them the safe batching appstore's non-native
1041 // classes proved out — 20 classes share one JVM + Robolectric
1042 // sandbox instead of the Gradle default (one JVM for the whole
1043 // suite, sequentially), with at most 3 such JVMs in parallel at
1044 // 1 GB each. The tighter fork cap (1..3, vs 1..6 for the
1045 // forkEvery = 1 path below) bounds the memory of several
1046 // long-lived Robolectric JVMs sitting side by side.
1047 //
1048 // WARNING: a shared JVM is shared state. appstore showed that
1049 // classes leaking viewModelScope collectors onto a process-wide
1050 // DataStore, or persisting DataStore/Room state another class
1051 // expects to be fresh, can hang or fail when batched — such
1052 // classes must not be enabled for this path without an audit
1053 // (Rust modules quarantine them via rustNativeTests
1054 // isolatedClasses instead; a non-Rust module that turns out to
1055 // pollute must be investigated, not silently kept batched).
1056 //
1057 // A Rust module with hostTests = false registers no ref but is
1058 // in rustNativeLibProjectPaths: leave it entirely alone.
1059 val isRustModule = (listOf(self.path) + ordered)
1060 .any { it in rustNativeLibProjectPaths() }
1061 if (!isRustModule) {
1062 self.tasks.withType<Test>().configureEach {
1063 forkEvery = 20
1064 maxParallelForks =
1065 (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 3)
1066 maxHeapSize = "1g"
1067 }
1068 }
1069 return@afterEvaluate
1070 }
1071 self.tasks.withType<Test>().configureEach {
1072 refs.forEach { ref -> dependsOn("${ref.projectPath}:${ref.taskName}") }
1073 val sep = File.pathSeparator
1074 val existing = (systemProperties["java.library.path"] as? String)
1075 ?.split(sep).orEmpty()
1076 val merged = (existing + refs.map { it.libDir }).distinct()
1077 systemProperty("java.library.path", merged.joinToString(sep))
1078 // A JNI library can be bound to only one classloader per JVM. Plain JVM tests
1079 // load it via the app classloader and Robolectric tests via its sandbox loader,
1080 // so mixing both in one JVM fails with "already loaded in another classloader".
1081 // One JVM per test class keeps each loader's System.loadLibrary isolated.
1082 forkEvery = 1
1083 // forkEvery = 1 alone would run those per-class JVMs one at a time
1084 // (Gradle's default maxParallelForks = 1): e.g. appstore's 152 test
1085 // classes become 152 sequential JVM + Robolectric sandbox startups.
1086 // Run several class-forks concurrently instead. Each Robolectric
1087 // fork costs roughly 1-2 GB (JVM + sandbox + resources + JaCoCo),
1088 // so the cap is memory-bounded, not core-proportional: half the
1089 // processors, clamped to 1..6. On 6-vCPU / 14 GB CI that is 3
1090 // forks (~3-6 GB of test JVMs beside the Gradle daemon); on a
1091 // many-core dev box it still stops at 6. Computed from a plain
1092 // Int at configuration time, so the configuration cache is
1093 // unaffected. Applies per Test task: smaller rustNativeLib
1094 // modules get the same parallelism headroom but only ever fork
1095 // as many JVMs as they have test classes queued.
1096 maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 6)
1097 }
1098 splitNativeLoadingTests(self)
1099 }
1100}
1101
1102/**
1103 * The quarantine, quarantined: `forkEvery = 1` exists only because a JNI
1104 * library binds to one classloader per JVM (see [wireRustHostLibsForUnitTests]),
1105 * yet it was applied to every test class in every [rustNativeLib] module —
1106 * appstore paid 152 sequential JVM + Robolectric sandbox startups for the
1107 * one class that actually loads `libappstore_signify`. A single [Test] task
1108 * cannot vary its fork cadence per class, so an opted-in module gets two:
1109 *
1110 * - the AGP task (`testDevUnitTest`, ...), excluding the native-loading
1111 * classes and running the rest with `forkEvery = 20` (the
1112 * `maxParallelForks` formula set above is unchanged);
1113 * - a companion `<task>Native` task including only those classes, keeping
1114 * `forkEvery = 1`.
1115 *
1116 * The AGP task depends on its companion, so existing invocations —
1117 * `./gradlew :appstore:testDevUnitTest`, `check`, the merged-coverage
1118 * task's `dependsOn("testDevUnitTest")` — still run the union of both
1119 * class sets; no test is dropped from the task CI already names. The
1120 * companion copies the AGP task's classes/classpath (their `builtBy`
1121 * edges still drive compilation) and is itself a [Test] task, so the
1122 * `configureEach` wiring above gives it the host cargo builds and the
1123 * merged `java.library.path` too.
1124 *
1125 * Opt-in only (see [RustNativeTestsExtension]): without explicit classes,
1126 * explicit patterns, `-Pmodernapps.nativeTestClasses=<fqcn>[,...]`, or
1127 * `split = true`, the module keeps the historic per-class fork for all
1128 * tests — the safe default for a module that has not audited which of
1129 * its classes load a native library.
1130 */
1131private fun Project.splitNativeLoadingTests(self: Project) {
1132 val extension = self.rustNativeTestsExtension()
1133 val propertyClasses = self.providers.gradleProperty("modernapps.nativeTestClasses").orNull
1134 ?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty()
1135 val explicitClasses = (extension.nativeClasses.get() + propertyClasses).distinct()
1136 val explicitPatterns = extension.nativePatterns.get()
1137 val isolatedClasses = extension.isolatedClasses.get().distinct()
1138 if (!extension.split.get() && explicitClasses.isEmpty() && explicitPatterns.isEmpty() &&
1139 isolatedClasses.isEmpty()
1140 ) return
1141
1142 fun classPatterns(fqcns: List<String>) = fqcns.flatMap { fqcn ->
1143 val path = fqcn.replace('.', '/')
1144 listOf("$path.class", "$path\$*.class")
1145 }
1146 // One quarantine pattern set: native loaders and isolated polluters both
1147 // keep forkEvery = 1 in the companion; everything else batches.
1148 val nativePatterns = (DEFAULT_NATIVE_TEST_PATTERNS + explicitPatterns +
1149 classPatterns(explicitClasses) + classPatterns(isolatedClasses)).distinct()
1150 val parallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 6)
1151
1152 // Snapshot: registering the companions below mutates the live collection.
1153 val mainTasks = self.tasks.withType<Test>()
1154 .filter { !it.name.endsWith(NATIVE_TEST_TASK_SUFFIX) }
1155 mainTasks.forEach { main ->
1156 val nativeName = main.name + NATIVE_TEST_TASK_SUFFIX
1157 if (self.tasks.findByName(nativeName) == null) {
1158 self.tasks.register<Test>(nativeName) {
1159 group = "verification"
1160 description = "Runs the ${main.name} classes quarantined to one JVM " +
1161 "per class (Rust native loaders and isolated polluters)."
1162 testClassesDirs = main.testClassesDirs
1163 classpath = main.classpath
1164 maxHeapSize = main.maxHeapSize
1165 minHeapSize = main.minHeapSize
1166 jvmArgs = main.jvmArgs
1167 systemProperties = main.systemProperties
1168 include(nativePatterns)
1169 // A `--tests` filter naming only main-task classes must not
1170 // fail this task for finding nothing to run.
1171 filter { isFailOnNoMatchingTests = false }
1172 forkEvery = 1
1173 maxParallelForks = parallelForks
1174 }
1175 }
1176 main.exclude(nativePatterns)
1177 // Batch classes that never load a native library: 20 classes share
1178 // one JVM + Robolectric sandbox instead of paying a startup each.
1179 main.forkEvery = 20
1180 main.maxParallelForks = parallelForks
1181 main.dependsOn(nativeName)
1182 }
1183}