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

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

RustNative.kt1215 lines · 62.2 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 // Fast (dev) profile only: unify the remap prefix across crates
515 // (below) so rustc command lines for shared dependencies are
516 // identical in every crate, and route rustc through sccache when
517 // it is installed (~/.cargo/bin/sccache, shared cache dir across
518 // worktrees). Isolated per-crate target dirs stay, so cargo
519 // builds remain parallel; sccache, not a shared target dir,
520 // provides the sharing (a shared dir serialises every cargo on
521 // its file lock and measured slower cold). Release is untouched
522 // (per-crate remap, no wrapper) and stays byte-reproducible.
523 val devSharedTarget = profile == "fast"
524 val effectiveTargetDir = isolatedTargetDir
525 val effectiveSoOut = effectiveTargetDir?.let { File(it, "$triple/$profile/lib$crate.so") }
526 val effectiveRemapLabel = if (devSharedTarget) "ma-dev" else remapLabel
527 val sccacheExe = if (devSharedTarget && File("$cargoBin/sccache").isFile) "$cargoBin/sccache" else null
528 val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/lib$crate.so").get().asFile
529 val targetRustflags = "-C link-arg=-Wl,-z,max-page-size=16384"
530
531 // Cacheable + relocatable: every input is RELATIVE-sensitive with a
532 // distinct property name, and toolchain facts the env doesn't cover
533 // (Exec treats environment/workingDir as @Internal, so env vars are
534 // NOT in the cache key) are explicit input properties. A fresh
535 // worktree at a different absolute path then restores FROM-CACHE.
536 outputs.cacheIf("Rust cdylib build is hermetic given the declared inputs") { true }
537
538 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
539 .withPropertyName("crateSrc")
540 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
541 .withPropertyName("crateManifest")
542 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
543 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
544 .withPropertyName("buildRs")
545 }
546 // The crate include_bytes!s build/spirv, so a shader edit must re-run cargo;
547 // otherwise the task stays up to date and the old SPIR-V silently ships.
548 compileShaders?.let {
549 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
550 .withPropertyName("spirv")
551 }
552 // `:library:ml`'s build.rs also compiles `schema/maml2.fbs` to Rust via
553 // flatc and `include!`s the result, so a schema edit changes the .so too.
554 // Same staleness hazard as shaders above: without this the task stays up
555 // to date and the old bindings ship.
556 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
557 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
558 .withPropertyName("schema")
559 }
560 // Whole-crate safety net: track every source under src/main/rust so ANY
561 // rust change invalidates cargoBuild - crucially vendored dependency
562 // crates under vendor/, which
563 // the path-specific inputs above do NOT cover. Before this, editing a
564 // vendored crate left the task UP-TO-DATE and shipped a stale .so. Exclude
565 // target/ because cargo writes this task's own .so there; folding build
566 // output back in as an input means the task can never be up to date. The
567 // FileTree is a FileCollection resolved at configuration time, so only the
568 // file set (never the Project) crosses into the task action.
569 inputs.files(fileTree(srcDir) { exclude("target/**") })
570 .withPathSensitivity(PathSensitivity.RELATIVE)
571 .withPropertyName("rustCrateTree")
572 // Cross-crate path deps (euicc -> jni-http, camera -> vision,
573 // maps -> tilecodec, ...): an edit there must rebuild this .so.
574 // Parsed generically from Cargo.toml `path =` + `workspace = true`
575 // entries (see findRustPathDepDirs), one input tree per dep crate.
576 for (depDir in pathDepDirs) {
577 val relDep = depDir.relativeTo(rootProject.projectDir)
578 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
579 .withPathSensitivity(PathSensitivity.RELATIVE)
580 .withPropertyName(pathDepPropertyName(rootProject.projectDir, depDir))
581 }
582 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
583 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
584 .withPropertyName("workspaceManifest")
585 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
586 .withPropertyName("workspaceLock")
587 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
588 .withPropertyName("rustToolchain")
589 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
590 // jni is a crates.io dependency now, so Cargo.lock above covers it.
591 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
592 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiSrc")
593 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
594 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiManifest")
595 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
596 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiBuildRs")
597 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
598 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("omFfiC")
599 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
600 inputs.dir(rootProject.file("third_party/betocore"))
601 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("betocore")
602 // Toolchain facts that shape the .so bytes but live in env/workingDir
603 // (both @Internal on Exec), so they need explicit input properties.
604 inputs.property("ndkVersion", NDK_VERSION)
605 inputs.property("hostTag", hostTag)
606 inputs.property("androidApiLevel", androidApiLevel)
607 inputs.property("targetRustflags", targetRustflags)
608 // The cargo profile shapes the .so bytes and the incremental
609 // setting below, and Exec environment is @Internal, so declare
610 // both as inputs: switching fast/release must re-run the task.
611 inputs.property("cargoProfile", profile)
612 inputs.property("cargoIncremental", profile == "fast" && sccacheExe == null)
613 inputs.property("rustRemapLabel", effectiveRemapLabel)
614 inputs.property("rustcWrapperSccache", sccacheExe != null)
615 // (cargoIncremental above already reflects this: sccache
616 // prohibits incremental compilation outright, so the wrapper
617 // replaces it — shared deps come from the sccache cache, and
618 // only the edited crate itself compiles in full.)
619 outputs.file(destSo)
620
621 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
622 val rustSrc = file(srcDir).absolutePath
623
624 val pathSep = if (isWindows) ";" else ":"
625 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
626 // A non-rustup rustc earlier on PATH (e.g. Homebrew's) has no
627 // aarch64-linux-android std, so cargo fails with "can't find crate for core".
628 // Pin the rustup shim explicitly.
629 environment("RUSTC", "$cargoBin/rustc$exeExt")
630 // The per-API NDK clang wrapper bakes in --target and the sysroot.
631 environment("CC", clang)
632 environment("CXX", clangpp)
633 environment("AR", "$ndkBin/llvm-ar$exeExt")
634 environment("SYSROOT", ndkSysroot)
635 environment(linkerVar, clang)
636 // Android 15 requires 16 KB page alignment on arm64 (Play blocks
637 // 4 KB .so files). Target-scoped so host build-script links on
638 // MSVC are unaffected. See analysis/plan-16kb-page-size.md.
639 val rustflagsVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_RUSTFLAGS"
640 environment(rustflagsVar, targetRustflags)
641 // Force the system clang for host-side C on Unix; on Windows let cc locate MinGW gcc.
642 if (!isWindows) environment("HOST_CC", "/usr/bin/clang")
643 // Pre-generated bindings (armv8-only): weather's om-file-format-sys no longer uses bindgen
644 // (bindings_android.rs/host checked in), so BINDGEN_EXTRA_CLANG_ARGS is no longer needed for build.
645 // Kept as comment for documentation if future C sys crates added.
646 // environment("BINDGEN_EXTRA_CLANG_ARGS", "--target=$triple$androidApiLevel --sysroot=$ndkSysroot")
647 // Reproducible builds: remap $HOME-specific paths (cargo registry + crate
648 // dir) to fixed constants so different machines produce identical .so bytes.
649 val remapBase = if (devSharedTarget) rootProject.projectDir.absolutePath else rustSrc
650 environment(
651 "RUSTFLAGS",
652 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$remapBase=/$effectiveRemapLabel",
653 )
654 environment("CFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$remapBase=/$effectiveRemapLabel -Wdate-time -Werror=date-time")
655 environment("CXXFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$remapBase=/$effectiveRemapLabel -Wdate-time -Werror=date-time")
656 environment("CPPFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$remapBase=/$effectiveRemapLabel -Wdate-time -Werror=date-time")
657 environment("ZERO_AR_DATE", "1")
658 // Reproducible builds: respect SOURCE_DATE_EPOCH if set (exported by the release build)
659 // https://reproducible-builds.org/docs/source-date-epoch/
660 System.getenv("SOURCE_DATE_EPOCH")?.takeIf { it.isNotBlank() }?.let {
661 environment("SOURCE_DATE_EPOCH", it)
662 }
663 // Release .so files must stay byte-reproducible, so release
664 // builds keep incremental off. The fast (dev) profile is never
665 // shipped, so it reuses incremental artifacts across edits.
666 environment("CARGO_INCREMENTAL", if (profile == "fast" && sccacheExe == null) "1" else "0")
667 effectiveTargetDir?.let { environment("CARGO_TARGET_DIR", it.absolutePath) }
668 sccacheExe?.let { environment("RUSTC_WRAPPER", it) }
669
670 commandLine(
671 "$cargoBin/cargo$exeExt",
672 "build",
673 "--locked",
674 "--profile",
675 profile,
676 "--target",
677 triple,
678 *cargoFeatureArgs.toTypedArray(),
679 )
680
681 doLast {
682 destSo.parentFile.mkdirs()
683 val src = when {
684 effectiveSoOut != null -> effectiveSoOut.takeIf { it.exists() }
685 ?: error("cargo produced no ${effectiveSoOut.path} for $crate")
686 perCrateSoOut.exists() -> perCrateSoOut
687 workspaceSoOut.exists() -> workspaceSoOut
688 else -> error("Neither per-crate ${perCrateSoOut.path} nor workspace ${workspaceSoOut.path} exists for $crate")
689 }
690 src.copyTo(destSo, overwrite = true)
691 }
692 }
693 }
694
695 val cargoNdkBuild = tasks.register("cargoNdkBuild_$crate") {
696 description = "Builds lib$crate.so for all Android ABIs."
697 dependsOn(perAbi)
698 }
699 // Keep the historic aggregate name for the default crate dir so existing
700 // invocations (`./gradlew :mod:cargoNdkBuild`) keep working.
701 if (srcDir == "src/main/rust") {
702 tasks.register("cargoNdkBuild") {
703 description = "Builds lib$crate.so for all Android ABIs."
704 dependsOn(cargoNdkBuild)
705 }
706 }
707 // Host cdylib for JVM unit tests (testDevUnitTest / testDevUnitTest):
708 // `cargo build --locked --target <hostTriple>` with the same profile,
709 // features, env (RUSTC pin, PATH, RUSTFLAGS remap, profile-keyed
710 // CARGO_INCREMENTAL),
711 // toolchain lock, inputs/outputs, and caching as the per-ABI tasks above —
712 // but WITHOUT any Android linker/NDK env (no CC/CXX/AR/SYSROOT, no
713 // per-target LINKER/RUSTFLAGS, no 16 KB page-size link arg: that flag
714 // would break the host link). The output (`lib<crate>.dylib/.so/.dll`)
715 // is installed into `build/rustHostLibs`, which nothing packages — APK/AAB
716 // assembly reads only `build/rustJniLibs`, so Android outputs are
717 // unchanged. Lazy by construction: nothing depends on this task except
718 // unit Test tasks (see wireRustHostLibsForUnitTests), so assemble/install
719 // never build it. With hostTests = false nothing is registered and
720 // dependents' tests never notice the crate.
721 val hostTriple: String = hostRustTriple()
722 val hostTaskName = "cargoBuildHost_$crate"
723 if (hostTests) {
724 val cargoBuildHost = tasks.register<Exec>(hostTaskName) {
725 usesService(rustLock)
726 description = "Builds lib$crate for the host (JVM unit tests)."
727 workingDir = file(srcDir)
728
729 val isWindowsHost = OperatingSystem.current().isWindows
730 val exeExt = if (isWindowsHost) ".exe" else ""
731 val hostLibName = hostRustLibFileName(crate)
732 // Per-crate target (may exist from older isolated builds) and workspace root target
733 // (current scheme since Cargo.toml workspace unified to root).
734 val perCrateHostOut = file("$srcDir/target/$hostTriple/$profile/$hostLibName")
735 val workspaceHostOut = rootProject.file("target/$hostTriple/$profile/$hostLibName")
736 val destHostLib = layout.buildDirectory.file("rustHostLibs/$hostLibName").get().asFile
737
738 // Same cacheable + relocatable shape as the per-ABI tasks: every
739 // input is RELATIVE-sensitive with a distinct (host-prefixed)
740 // property name, and host-toolchain facts the env doesn't cover
741 // are explicit input properties.
742 outputs.cacheIf("Rust cdylib host build is hermetic given the declared inputs") { true }
743
744 inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)
745 .withPropertyName("hostCrateSrc")
746 inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)
747 .withPropertyName("hostCrateManifest")
748 file("$srcDir/build.rs").takeIf { it.isFile }?.let {
749 inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)
750 .withPropertyName("hostBuildRs")
751 }
752 // Same SPIR-V staleness hazard as the ABI tasks: the crate
753 // include_bytes!s build/spirv, so a shader edit must re-run cargo.
754 compileShaders?.let {
755 inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)
756 .withPropertyName("hostSpirv")
757 }
758 // Same flatc-bindings staleness hazard as the ABI tasks (see above).
759 file("$srcDir/schema").takeIf { it.isDirectory }?.let {
760 inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)
761 .withPropertyName("hostSchema")
762 }
763 inputs.files(fileTree(srcDir) { exclude("target/**") })
764 .withPathSensitivity(PathSensitivity.RELATIVE)
765 .withPropertyName("hostRustCrateTree")
766 for (depDir in pathDepDirs) {
767 val relDep = depDir.relativeTo(rootProject.projectDir)
768 inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })
769 .withPathSensitivity(PathSensitivity.RELATIVE)
770 .withPropertyName("host_" + pathDepPropertyName(rootProject.projectDir, depDir))
771 }
772 // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)
773 inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
774 .withPropertyName("hostWorkspaceManifest")
775 inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)
776 .withPropertyName("hostWorkspaceLock")
777 inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)
778 .withPropertyName("hostRustToolchain")
779 // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).
780 // jni is a crates.io dependency now, so Cargo.lock above covers it.
781 inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))
782 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiSrc")
783 inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))
784 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiManifest")
785 inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
786 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiBuildRs")
787 inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))
788 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiC")
789 // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.
790 inputs.dir(rootProject.file("third_party/betocore"))
791 .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostBetocore")
792 // Host-toolchain facts that shape the lib bytes but live in env/workingDir
793 // (both @Internal on Exec), so they need an explicit input property.
794 // Deliberately NOT the NDK props: the host link must not see them.
795 inputs.property("hostTriple", hostTriple)
796 inputs.property("cargoProfile", profile)
797 inputs.property("cargoIncremental", profile == "fast")
798 outputs.file(destHostLib)
799
800 val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"
801 val rustSrc = file(srcDir).absolutePath
802
803 val pathSep = if (isWindowsHost) ";" else ":"
804 environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")
805 // Same non-rustup-rustc hazard as the ABI tasks: pin the shim.
806 environment("RUSTC", "$cargoBin/rustc$exeExt")
807 // Reproducible builds: same $HOME remap as the ABI tasks.
808 environment(
809 "RUSTFLAGS",
810 "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",
811 )
812 environment("CARGO_INCREMENTAL", if (profile == "fast") "1" else "0")
813
814 commandLine(
815 "$cargoBin/cargo$exeExt",
816 "build",
817 "--locked",
818 "--profile",
819 profile,
820 "--target",
821 hostTriple,
822 *cargoFeatureArgs.toTypedArray(),
823 )
824
825 doLast {
826 destHostLib.parentFile.mkdirs()
827 val src = when {
828 perCrateHostOut.exists() -> perCrateHostOut
829 workspaceHostOut.exists() -> workspaceHostOut
830 else -> error("Neither per-crate ${perCrateHostOut.path} nor workspace ${workspaceHostOut.path} exists for $crate")
831 }
832 src.copyTo(destHostLib, overwrite = true)
833 }
834 }
835 // Same historic-aggregate convenience as cargoNdkBuild for the default
836 // crate dir (`./gradlew :mod:cargoBuildHost`); per-crate task names stay
837 // unique for multi-crate modules (communicate's rust-mls second crate).
838 if (srcDir == "src/main/rust") {
839 tasks.register("cargoBuildHost") {
840 description = "Builds lib$crate for the host (JVM unit tests)."
841 dependsOn(cargoBuildHost)
842 }
843 }
844 // Recorded for wireRustHostLibsForUnitTests: plain strings only, so the
845 // configuration cache never sees a Project.
846 rustHostLibRefs().getOrPut(path) { mutableListOf() } += RustHostLibRef(
847 projectPath = path,
848 taskName = hostTaskName,
849 libDir = layout.buildDirectory.dir("rustHostLibs").get().asFile.absolutePath,
850 )
851 } else {
852 logger.warn("rustNativeLib($crate): hostTests = false — JVM unit tests cannot load this crate.")
853 }
854 // Rust file-length gate: fails the build on any *.rs over
855 // RUST_FILE_LENGTH_LIMIT lines, like the Kotlin FileLength rule (which
856 // cannot see Rust). Configuration-cache compatible: plain path strings
857 // cross the configuration boundary, never the Project object.
858 val rustSrcPath: String = file("$srcDir/src").absolutePath
859 val rustProjPath: String = projectDir.absolutePath
860 val lengthTaskName = if (srcDir == "src/main/rust") "rustFileLength" else "rustFileLength_$crate"
861 val rustFileLength = tasks.register(lengthTaskName) {
862 description = "Fails on Rust files over $RUST_FILE_LENGTH_LIMIT lines."
863 inputs.dir(rustSrcPath)
864 doLast {
865 val srcDir = java.io.File(rustSrcPath)
866 val projDir = java.io.File(rustProjPath)
867 val over = srcDir.walkTopDown()
868 .filter { it.isFile && it.extension == "rs" }
869 .map { it to it.readLines().size }
870 .filter { (f, n) ->
871 n > RUST_FILE_LENGTH_LIMIT &&
872 f.name !in RUST_LENGTH_EXEMPT_FILES &&
873 !isRustLengthExempt(f.path)
874 }
875 .toList()
876 if (over.isNotEmpty()) {
877 val detail = over.joinToString("\n") { (f, n) ->
878 " $n ${f.relativeTo(projDir)}"
879 }
880 throw org.gradle.api.GradleException(
881 "Rust files exceed $RUST_FILE_LENGTH_LIMIT lines (split along module lines):\n$detail"
882 )
883 }
884 }
885 }
886 tasks.matching { it.name == "preBuild" }.configureEach {
887 dependsOn(cargoNdkBuild)
888 dependsOn(rustFileLength)
889 }
890}
891
892/**
893 * One host-testable crate registered by [rustNativeLib]: the owning project's
894 * path, the host build task name, and the `build/rustHostLibs` dir. Plain
895 * strings only, so the configuration cache never sees a Project.
896 */
897data class RustHostLibRef(
898 val projectPath: String,
899 val taskName: String,
900 val libDir: String,
901)
902
903/**
904 * Project paths of every module that called [rustNativeLib], host-testable
905 * or not. Plain Strings in the root extra properties, mirroring
906 * [rustHostLibRefs], so the configuration cache never sees a Project.
907 */
908private fun Project.rustNativeLibProjectPaths(): MutableSet<String> {
909 val extra = rootProject.extensions.extraProperties
910 @Suppress("UNCHECKED_CAST")
911 return if (extra.has("rustNativeLibProjectPaths")) {
912 extra.get("rustNativeLibProjectPaths") as MutableSet<String>
913 } else {
914 mutableSetOf<String>().also { extra.set("rustNativeLibProjectPaths", it) }
915 }
916}
917
918/** Shared `projectPath -> host crates` registry (see [RustHostLibRef]). */
919private fun Project.rustHostLibRefs(): MutableMap<String, MutableList<RustHostLibRef>> {
920 val extra = rootProject.extensions.extraProperties
921 @Suppress("UNCHECKED_CAST")
922 return if (extra.has("rustHostLibRefs")) {
923 extra.get("rustHostLibRefs") as MutableMap<String, MutableList<RustHostLibRef>>
924 } else {
925 mutableMapOf<String, MutableList<RustHostLibRef>>().also { extra.set("rustHostLibRefs", it) }
926 }
927}
928
929/**
930 * Per-module opt-in for splitting native-loading unit tests out of the main
931 * unit-test task (see [wireRustHostLibsForUnitTests]).
932 *
933 * A test class belongs in the native split when executing it can actually
934 * `System.loadLibrary` a Rust cdylib — directly, or through the module's
935 * `<Feature>Native` wrapper / a facade over it (e.g. appstore's
936 * `Signify.verify` -> `SignifyNative`). Classes that merely reference a
937 * repository whose native path is stubbed out in the test do NOT load the
938 * library and stay in the main task.
939 */
940abstract class RustNativeTestsExtension {
941 /**
942 * Fully-qualified names of test classes that load a Rust native library.
943 * Each name also matches its nested classes. Naming a class here (or
944 * adding [nativePatterns]) enables the split for the module.
945 */
946 abstract val nativeClasses: ListProperty<String>
947
948 /**
949 * Extra class-file include patterns for native-loading tests, in Gradle
950 * [Test] include syntax (glob patterns over class-file paths). Added to
951 * the built-in conventions in [DEFAULT_NATIVE_TEST_PATTERNS].
952 */
953 abstract val nativePatterns: ListProperty<String>
954
955 /**
956 * Fully-qualified names of test classes that must keep one-JVM-per-class
957 * for a non-JNI reason: they pollute a shared JVM (leaked
958 * `viewModelScope` collectors on the process-wide DataStores, persisted
959 * DataStore files, process-wide flows) or depend on that state being
960 * fresh. Each name also matches its nested classes. These classes join
961 * the same per-class companion task as [nativeClasses]; the companion
962 * is a quarantine, whatever the reason a class needs its own JVM.
963 */
964 abstract val isolatedClasses: ListProperty<String>
965
966 /**
967 * Enables the split even with no explicit classes/patterns, relying only
968 * on the built-in naming/package conventions. Defaults to false: modules
969 * that have not audited which classes load a native library keep the
970 * historic one-JVM-per-class behaviour for every test.
971 */
972 abstract val split: Property<Boolean>
973}
974
975/** DSL entry point for [RustNativeTestsExtension], e.g. in a module build file. */
976fun Project.rustNativeTests(configure: RustNativeTestsExtension.() -> Unit) {
977 rustNativeTestsExtension().configure()
978}
979
980private fun Project.rustNativeTestsExtension(): RustNativeTestsExtension =
981 extensions.findByType(RustNativeTestsExtension::class.java)
982 ?: extensions.create("rustNativeTests", RustNativeTestsExtension::class.java)
983
984/** Suffix of the per-class-fork companion task of a unit-test task (`testDevUnitTest` -> `testDevUnitTestNative`). */
985const val NATIVE_TEST_TASK_SUFFIX = "Native"
986
987/**
988 * Built-in conventions for native-loading test classes, as class-file
989 * patterns: a test type named `*Native*Test(s)` in any package, or any test
990 * type under a `native` package segment. Deliberately narrow — a class that
991 * matches but never actually loads a library only costs itself a dedicated
992 * JVM, while the explicit [RustNativeTestsExtension.nativeClasses] list is
993 * the precise mechanism for loaders that follow neither convention
994 * (appstore's `FingerprintNormalizeTest` reaches `SignifyNative` through
995 * `Signify.verify`).
996 */
997val DEFAULT_NATIVE_TEST_PATTERNS: List<String> = listOf(
998 "**/*NativeTest.class",
999 "**/*NativeTest\$*.class",
1000 "**/*NativeTests.class",
1001 "**/*NativeTests\$*.class",
1002 "**/native/**Test.class",
1003 "**/native/**Test\$*.class",
1004 "**/native/**Tests.class",
1005 "**/native/**Tests\$*.class",
1006)
1007
1008/**
1009 * Wires every unit [Test] task (testDevUnitTest, testDebugUnitTest, ...) so
1010 * `System.loadLibrary` finds Rust cdylibs on the host JVM: each Test task
1011 * depends on the host build tasks of this module and of every project it
1012 * transitively depends on that registered one via [rustNativeLib]
1013 * (e.g. `:office` also picks up `:library:e2ee-p2p`'s `e2ee_pqc`), and
1014 * `java.library.path` gains each of their `build/rustHostLibs` dirs.
1015 *
1016 * The existing value is appended to, never clobbered: AGP's own
1017 * `src/test/jniLibs` dirs (which AGP merges into the same property) survive
1018 * regardless of ordering, because both sides merge. Crates opted out with
1019 * `hostTests = false` register no task and are skipped cleanly.
1020 *
1021 * Laziness: the host tasks are reachable only through these `dependsOn`
1022 * edges, so assemble/install never build them. Configuration-cache safe:
1023 * `evaluationDependsOn` pulls transitive deps through evaluation before any
1024 * state is read, and only plain strings (task paths, dir paths) cross into
1025 * task configuration — never a Project.
1026 *
1027 * Dual role: this is also where the app/library conventions get their
1028 * non-Rust Test batching. When neither this project nor any project dep
1029 * registered a host lib (and none called [rustNativeLib] at all), the
1030 * afterEvaluate below configures every Test task with `forkEvery = 20`,
1031 * `maxParallelForks = (cores / 2).coerceIn(1, 3)` and `maxHeapSize = "1g"`.
1032 * When a Rust module is involved it returns without touching the task —
1033 * the `forkEvery = 1` wiring below (and the rustNativeTests split) owns it.
1034 */
1035fun Project.wireRustHostLibsForUnitTests() {
1036 // Created here, while the convention plugin is being applied, so the
1037 // module's own build file (evaluated afterwards) can configure it via
1038 // `rustNativeTests { ... }`. Read only in afterEvaluate below, when the
1039 // module's values are final.
1040 rustNativeTestsExtension().split.convention(false)
1041 // Deferred to afterEvaluate: the module's own `dependencies {}` block runs
1042 // after the convention plugin, so the project-dep graph is only complete
1043 // then. Task wiring uses configureEach, which covers Test tasks whether
1044 // AGP already created them or creates them later.
1045 afterEvaluate {
1046 val self = this@wireRustHostLibsForUnitTests
1047 val ordered = mutableListOf<String>()
1048 val seen = HashSet<String>()
1049 seen += self.path
1050 val queue = ArrayDeque<String>()
1051 fun enqueueDepsOf(p: Project) {
1052 p.configurations.forEach { cfg ->
1053 cfg.dependencies.filterIsInstance<ProjectDependency>().forEach { dep ->
1054 val depPath = dep.path
1055 if (seen.add(depPath)) {
1056 queue += depPath
1057 ordered += depPath
1058 }
1059 }
1060 }
1061 }
1062 enqueueDepsOf(self)
1063 while (queue.isNotEmpty()) {
1064 val depPath = queue.removeFirst()
1065 self.evaluationDependsOn(depPath)
1066 enqueueDepsOf(self.project(depPath))
1067 }
1068 val refs = (listOf(self.path) + ordered).flatMap { rustHostLibRefs()[it].orEmpty() }
1069 if (refs.isEmpty()) {
1070 // Non-Rust modules (neither this project nor any project dep
1071 // called rustNativeLib): RustNative does not control these Test
1072 // tasks, so give them the safe batching appstore's non-native
1073 // classes proved out — 20 classes share one JVM + Robolectric
1074 // sandbox instead of the Gradle default (one JVM for the whole
1075 // suite, sequentially), with at most 3 such JVMs in parallel at
1076 // 1 GB each. The tighter fork cap (1..3, vs 1..6 for the
1077 // forkEvery = 1 path below) bounds the memory of several
1078 // long-lived Robolectric JVMs sitting side by side.
1079 //
1080 // WARNING: a shared JVM is shared state. appstore showed that
1081 // classes leaking viewModelScope collectors onto a process-wide
1082 // DataStore, or persisting DataStore/Room state another class
1083 // expects to be fresh, can hang or fail when batched — such
1084 // classes must not be enabled for this path without an audit
1085 // (Rust modules quarantine them via rustNativeTests
1086 // isolatedClasses instead; a non-Rust module that turns out to
1087 // pollute must be investigated, not silently kept batched).
1088 //
1089 // A Rust module with hostTests = false registers no ref but is
1090 // in rustNativeLibProjectPaths: leave it entirely alone.
1091 val isRustModule = (listOf(self.path) + ordered)
1092 .any { it in rustNativeLibProjectPaths() }
1093 if (!isRustModule) {
1094 self.tasks.withType<Test>().configureEach {
1095 forkEvery = 20
1096 maxParallelForks =
1097 (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 3)
1098 maxHeapSize = "1g"
1099 }
1100 }
1101 return@afterEvaluate
1102 }
1103 self.tasks.withType<Test>().configureEach {
1104 refs.forEach { ref -> dependsOn("${ref.projectPath}:${ref.taskName}") }
1105 val sep = File.pathSeparator
1106 val existing = (systemProperties["java.library.path"] as? String)
1107 ?.split(sep).orEmpty()
1108 val merged = (existing + refs.map { it.libDir }).distinct()
1109 systemProperty("java.library.path", merged.joinToString(sep))
1110 // A JNI library can be bound to only one classloader per JVM. Plain JVM tests
1111 // load it via the app classloader and Robolectric tests via its sandbox loader,
1112 // so mixing both in one JVM fails with "already loaded in another classloader".
1113 // One JVM per test class keeps each loader's System.loadLibrary isolated.
1114 forkEvery = 1
1115 // forkEvery = 1 alone would run those per-class JVMs one at a time
1116 // (Gradle's default maxParallelForks = 1): e.g. appstore's 152 test
1117 // classes become 152 sequential JVM + Robolectric sandbox startups.
1118 // Run several class-forks concurrently instead. Each Robolectric
1119 // fork costs roughly 1-2 GB (JVM + sandbox + resources + JaCoCo),
1120 // so the cap is memory-bounded, not core-proportional: half the
1121 // processors, clamped to 1..6. On 6-vCPU / 14 GB CI that is 3
1122 // forks (~3-6 GB of test JVMs beside the Gradle daemon); on a
1123 // many-core dev box it still stops at 6. Computed from a plain
1124 // Int at configuration time, so the configuration cache is
1125 // unaffected. Applies per Test task: smaller rustNativeLib
1126 // modules get the same parallelism headroom but only ever fork
1127 // as many JVMs as they have test classes queued.
1128 maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 6)
1129 }
1130 splitNativeLoadingTests(self)
1131 }
1132}
1133
1134/**
1135 * The quarantine, quarantined: `forkEvery = 1` exists only because a JNI
1136 * library binds to one classloader per JVM (see [wireRustHostLibsForUnitTests]),
1137 * yet it was applied to every test class in every [rustNativeLib] module —
1138 * appstore paid 152 sequential JVM + Robolectric sandbox startups for the
1139 * one class that actually loads `libappstore_signify`. A single [Test] task
1140 * cannot vary its fork cadence per class, so an opted-in module gets two:
1141 *
1142 * - the AGP task (`testDevUnitTest`, ...), excluding the native-loading
1143 * classes and running the rest with `forkEvery = 20` (the
1144 * `maxParallelForks` formula set above is unchanged);
1145 * - a companion `<task>Native` task including only those classes, keeping
1146 * `forkEvery = 1`.
1147 *
1148 * The AGP task depends on its companion, so existing invocations —
1149 * `./gradlew :appstore:testDevUnitTest`, `check`, the merged-coverage
1150 * task's `dependsOn("testDevUnitTest")` — still run the union of both
1151 * class sets; no test is dropped from the task CI already names. The
1152 * companion copies the AGP task's classes/classpath (their `builtBy`
1153 * edges still drive compilation) and is itself a [Test] task, so the
1154 * `configureEach` wiring above gives it the host cargo builds and the
1155 * merged `java.library.path` too.
1156 *
1157 * Opt-in only (see [RustNativeTestsExtension]): without explicit classes,
1158 * explicit patterns, `-Pmodernapps.nativeTestClasses=<fqcn>[,...]`, or
1159 * `split = true`, the module keeps the historic per-class fork for all
1160 * tests — the safe default for a module that has not audited which of
1161 * its classes load a native library.
1162 */
1163private fun Project.splitNativeLoadingTests(self: Project) {
1164 val extension = self.rustNativeTestsExtension()
1165 val propertyClasses = self.providers.gradleProperty("modernapps.nativeTestClasses").orNull
1166 ?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty()
1167 val explicitClasses = (extension.nativeClasses.get() + propertyClasses).distinct()
1168 val explicitPatterns = extension.nativePatterns.get()
1169 val isolatedClasses = extension.isolatedClasses.get().distinct()
1170 if (!extension.split.get() && explicitClasses.isEmpty() && explicitPatterns.isEmpty() &&
1171 isolatedClasses.isEmpty()
1172 ) return
1173
1174 fun classPatterns(fqcns: List<String>) = fqcns.flatMap { fqcn ->
1175 val path = fqcn.replace('.', '/')
1176 listOf("$path.class", "$path\$*.class")
1177 }
1178 // One quarantine pattern set: native loaders and isolated polluters both
1179 // keep forkEvery = 1 in the companion; everything else batches.
1180 val nativePatterns = (DEFAULT_NATIVE_TEST_PATTERNS + explicitPatterns +
1181 classPatterns(explicitClasses) + classPatterns(isolatedClasses)).distinct()
1182 val parallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 6)
1183
1184 // Snapshot: registering the companions below mutates the live collection.
1185 val mainTasks = self.tasks.withType<Test>()
1186 .filter { !it.name.endsWith(NATIVE_TEST_TASK_SUFFIX) }
1187 mainTasks.forEach { main ->
1188 val nativeName = main.name + NATIVE_TEST_TASK_SUFFIX
1189 if (self.tasks.findByName(nativeName) == null) {
1190 self.tasks.register<Test>(nativeName) {
1191 group = "verification"
1192 description = "Runs the ${main.name} classes quarantined to one JVM " +
1193 "per class (Rust native loaders and isolated polluters)."
1194 testClassesDirs = main.testClassesDirs
1195 classpath = main.classpath
1196 maxHeapSize = main.maxHeapSize
1197 minHeapSize = main.minHeapSize
1198 jvmArgs = main.jvmArgs
1199 systemProperties = main.systemProperties
1200 include(nativePatterns)
1201 // A `--tests` filter naming only main-task classes must not
1202 // fail this task for finding nothing to run.
1203 filter { isFailOnNoMatchingTests = false }
1204 forkEvery = 1
1205 maxParallelForks = parallelForks
1206 }
1207 }
1208 main.exclude(nativePatterns)
1209 // Batch classes that never load a native library: 20 classes share
1210 // one JVM + Robolectric sandbox instead of paying a startup each.
1211 main.forkEvery = 20
1212 main.maxParallelForks = parallelForks
1213 main.dependsOn(nativeName)
1214 }
1215}