lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 3d9f666bf9e9f66d1ade4293c516f03c88caf35a
parent 0ba661c25ae701ebbf40f574a02074cf3c035420
Author: triesap <tyson@radroots.org>
Date:   Wed, 21 Oct 2026 05:56:28 +0000

sdk_generation: preserve native lifecycle and error fields

- Route retained SDK artifacts through source-owned binding generation.
- Preserve async close and native Kotlin exception message fields.
- Bind generator source and qualify actual strict Swift and Kotlin calls.
- Retain exact generic native artifacts and execute the SDK producer case.

Diffstat:
Mcrates/sdk_ffi/README.md | 12++++++++++++
Acrates/sdk_ffi/tests/native/Smoke.kt | 22++++++++++++++++++++++
Acrates/sdk_ffi/tests/native/Smoke.swift | 35+++++++++++++++++++++++++++++++++++
Acrates/sdk_ffi/tests/native/qualify.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/bin/radroots_ffi_bindgen/kotlin.rs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/bin/radroots_ffi_bindgen/main.rs | 22++++++++++++++++++++--
Mtools/xtask/src/sdk_generation/bindings.rs | 69+++++++++++++++++++++++++++++++++------------------------------------
7 files changed, 261 insertions(+), 38 deletions(-)

diff --git a/crates/sdk_ffi/README.md b/crates/sdk_ffi/README.md @@ -8,3 +8,15 @@ DTOs; those remain mobile-host responsibilities. This Rust build crate is never published. Generated Swift and Kotlin artifacts are qualified independently from the public 19-crate Rust inventory. + +The SDK artifact producer uses the source-owned `radroots_ffi_bindgen` binary +in `xtask`. It preserves the actual async close method, keeps native string +error messages as Kotlin's exception message, and gives Swift observer +cancellation an explicit safe lifetime. Generated files must never be patched +by consumers. Source-lock identity includes the generator implementation. + +`tests/native/qualify.mjs` accepts explicit library, generator, output, Kotlin, +JNA and Java paths. It checks repeated generation, strict Swift6/Kotlin +compilation, real native error-field round trips and actual memory-client +closure. That retained bridge test does not qualify participant custody or +application behavior. diff --git a/crates/sdk_ffi/tests/native/Smoke.kt b/crates/sdk_ffi/tests/native/Smoke.kt @@ -0,0 +1,22 @@ +import kotlinx.coroutines.runBlocking +import uniffi.radroots_sdk.MobileClient +import uniffi.radroots_sdk.Exception as SdkFailure +import uniffi.radroots_sdk.parseTradeEvidenceManifest + +fun main() = runBlocking { + try { + parseTradeEvidenceManifest(byteArrayOf(0)) + error("invalid manifest accepted") + } catch (failure: SdkFailure.Sdk) { + check(failure.code == "invalid_evidence_manifest") + check(failure.message == "evidence manifest is invalid") + check(!failure.retryable) + } + val client = MobileClient.memory() + check(!client.isClosed() && client.capabilities().isNotEmpty()) + client.close() + check(client.isClosed()) + client.close() + client.destroy() + println("retained Kotlin native fields and actual asynchronous lifecycle passed") +} diff --git a/crates/sdk_ffi/tests/native/Smoke.swift b/crates/sdk_ffi/tests/native/Smoke.swift @@ -0,0 +1,35 @@ +import Foundation + +enum SmokeFailure: Swift.Error { case failed(String) } +func check(_ value: Bool, _ message: String) throws { + if !value { throw SmokeFailure.failed(message) } +} +@main +struct Smoke { + static func main() async throws { + do { + _ = try parseTradeEvidenceManifest(canonicalBytes: Data([0])) + throw SmokeFailure.failed("invalid manifest accepted") + } catch let failure as Error { + switch failure { + case let .Sdk(code, message, retryable): + try check(code == "invalid_evidence_manifest" && message == "evidence manifest is invalid" && !retryable, "all original safe native error fields") + } + } + let client = try MobileClient.memory() + try check(!client.isClosed() && !client.capabilities().isEmpty, "actual retained memory client") + try await client.close() + try check(client.isClosed(), "actual asynchronous native close") + try await client.close() + let alreadyCancelled = Task { () throws -> Void in + withUnsafeCurrentTask { $0?.cancel() } + try await client.close() + } + do { + try await alreadyCancelled.value + throw SmokeFailure.failed("cancelled observer succeeded") + } catch is CancellationError { } + try await client.close() + print("retained Swift native fields, lifecycle and observer cancellation passed") + } +} diff --git a/crates/sdk_ffi/tests/native/qualify.mjs b/crates/sdk_ffi/tests/native/qualify.mjs @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {mkdirSync,readFileSync,readdirSync,writeFileSync} from 'node:fs'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const options=new Map();for(let i=2;i<process.argv.length;i+=2)options.set(process.argv[i],resolve(process.argv[i+1])); +for(const name of ['--out','--library','--generator','--kotlinc','--jna','--java'])assert(options.has(name),name); +const out=options.get('--out'),fixture=dirname(fileURLToPath(import.meta.url));mkdirSync(out,{recursive:false}); +const hash=path=>createHash('sha256').update(readFileSync(path)).digest('hex'); +const files=(root,prefix='')=>readdirSync(root,{withFileTypes:true}).flatMap(entry=>entry.isDirectory()?files(join(root,entry.name),join(prefix,entry.name)):[join(prefix,entry.name)]).sort(); +const library=options.get('--library'),generator=options.get('--generator'); +const report={state:'running',scope:'actual retained native SDK memory/field/lifecycle bridge; no participant, generic factory or application qualification',library:{path:library,sha256:hash(library)},generator:{path:generator,sha256:hash(generator)},commands:[]}; +function persist(){writeFileSync(join(out,'report.json'),JSON.stringify(report,null,2)+'\n');} +function run(command,args){ + const start=performance.now(),result=spawnSync(command,args,{encoding:'utf8',maxBuffer:8*1024*1024,timeout:240000}); + const log=join(out,`${report.commands.length}.log`);writeFileSync(log,(result.stdout||'')+(result.stderr||'')); + const row={command:[command,...args],exit_code:result.status,signal:result.signal,error:result.error?.message,seconds:(performance.now()-start)/1000,log,sha256:hash(log)}; + report.commands.push(row);persist();assert(!result.error&&result.status===0,readFileSync(log,'utf8'));console.log(JSON.stringify(row)); +} +try{ + run(generator,['--version']);run('/usr/bin/swiftc',['--version']);run(options.get('--kotlinc'),['-version']); + for(const language of ['swift','kotlin']){ + const first=join(out,language),second=first+'_repeat'; + for(const target of [first,second])run(generator,['generate','--library',library,'--language',language,'--no-format','--out-dir',target]); + assert.deepEqual(files(first),files(second));for(const file of files(first))assert.equal(hash(join(first,file)),hash(join(second,file))); + report[language]=Object.fromEntries(files(first).map(file=>[file,hash(join(first,file))])); + } + const swift=join(out,'swift'),executable=join(out,'swift_smoke'); + run('/usr/bin/swiftc',['-swift-version','6','-warnings-as-errors','-parse-as-library','-I',swift,'-Xcc',`-fmodule-map-file=${join(swift,'radroots_sdkFFI.modulemap')}`,join(swift,'radroots_sdk.swift'),join(fixture,'Smoke.swift'),library,'-o',executable]); + run(executable,[]); + const coroutine=resolve(options.get('--kotlinc'),'../../lib/kotlinx-coroutines-core-jvm.jar'); + const classpath=[options.get('--jna'),coroutine].join(':'),jar=join(out,'kotlin_smoke.jar'); + report.runtimeJars=Object.fromEntries([options.get('--jna'),coroutine].map(path=>[path,hash(path)])); + run(options.get('--kotlinc'),[join(out,'kotlin/uniffi/radroots_sdk/radroots_sdk.kt'),join(fixture,'Smoke.kt'),'-Werror','-jvm-target','21','-classpath',classpath,'-include-runtime','-d',jar]); + run(options.get('--java'),[`-Djna.library.path=${dirname(library)}`,'-cp',[jar,classpath].join(':'),'SmokeKt']); + report.state='passed'; +}finally{persist();} diff --git a/tools/xtask/src/bin/radroots_ffi_bindgen/kotlin.rs b/tools/xtask/src/bin/radroots_ffi_bindgen/kotlin.rs @@ -6,6 +6,78 @@ use anyhow::{Result, ensure}; const SHIM: &str = " @Synchronized\n override fun close() {\n this.destroy()\n }\n"; +/// A native string field named `message` is the actual Throwable message. +/// Retain it and every converter field; remove only the conflicting diagnostic +/// getter generated by the pinned upstream template for that exact variant. +pub(super) fn preserve_error_messages( + source: &str, + variants: &[(String, String)], +) -> Result<String> { + let mut output = source.to_owned(); + for (error, variant) in variants { + let canonical = |name: &str| { + ensure!( + name.bytes().all(|v| v.is_ascii_alphanumeric()) + && name.as_bytes().first().is_some_and(u8::is_ascii_uppercase), + "unsupported Kotlin error naming" + ); + Ok::<_, anyhow::Error>( + name.strip_suffix("Error") + .map_or_else(|| name.to_owned(), |v| format!("{v}Exception")), + ) + }; + let error = canonical(error)?; + let variant = canonical(variant)?; + let header = format!("sealed class {error}: kotlin.Exception()"); + ensure!( + output.matches(&header).count() == 1, + "unexpected Kotlin error header" + ); + let start = output.find(&header).expect("counted error"); + let end = output[start..] + .find(" companion object ErrorHandler") + .ok_or_else(|| anyhow::anyhow!("unexpected Kotlin error boundary"))? + + start; + let declaration = format!("\n class {variant}("); + let body = &output[start..end]; + ensure!( + body.matches(&declaration).count() == 1, + "unexpected Kotlin error variant" + ); + let variant_start = body.find(&declaration).expect("counted variant") + start; + let variant_end = output[variant_start..end] + .find("\n }\n") + .ok_or_else(|| anyhow::anyhow!("unexpected Kotlin variant boundary"))? + + variant_start; + let body = &output[variant_start..variant_end]; + let field = " val `message`: kotlin.String"; + let getter = " override val message\n get() = \""; + ensure!( + body.matches(field).count() == 1 && body.matches(getter).count() == 1, + "unexpected Kotlin message field/getter" + ); + let getter_start = body.find(getter).expect("counted getter"); + let getter_end = body[getter_start..] + .find('\n') + .and_then(|first| { + body[getter_start + first + 1..] + .find('\n') + .map(|second| getter_start + first + 1 + second + 1) + }) + .unwrap_or(body.len()); + let removed = &body[getter_start..getter_end]; + ensure!( + removed.trim_end().ends_with('"') && removed.lines().count() == 2, + "unexpected Kotlin message getter layout" + ); + let mut replacement = + body[..getter_start].replace(field, " override val `message`: kotlin.String"); + replacement.push_str(&body[getter_end..]); + output.replace_range(variant_start..variant_end, &replacement); + } + Ok(output) +} + pub(super) fn preserve_close(source: &str, methods: &[(String, bool)]) -> Result<String> { let mut output = source.to_owned(); for (name, asynchronous) in methods { @@ -48,6 +120,34 @@ pub(super) fn preserve_close(source: &str, methods: &[(String, bool)]) -> Result #[cfg(test)] mod tests { use super::*; + fn error_source(name: &str, variant: &str) -> String { + format!( + "sealed class {name}: kotlin.Exception() {{\n class {variant}(\n val `code`: kotlin.String,\n val `message`: kotlin.String\n ) : {name}() {{\n override val message\n get() = \"code=${{ `code` }}, message=${{ `message` }}\"\n }}\n companion object ErrorHandler\n}}\n" + ) + } + #[test] + fn preserves_native_message_field_without_a_conflicting_diagnostic_getter() { + let metadata = [("Error".to_owned(), "Sdk".to_owned())]; + let untouched = error_source("OtherException", "Sdk"); + let source = format!("{}{untouched}", error_source("Exception", "Sdk")); + let actual = preserve_error_messages(&source, &metadata).unwrap(); + assert!(actual.starts_with("sealed class Exception")); + assert!(actual.contains("override val `message`: kotlin.String")); + assert!(actual.contains("val `code`: kotlin.String")); + assert_eq!(actual.matches(" override val message\n").count(), 1); + assert!(actual.ends_with(&untouched)); + assert!(preserve_error_messages(&actual, &metadata).is_err()); + assert!( + preserve_error_messages(&source.replace("kotlin.String", "kotlin.Int"), &metadata) + .is_err() + ); + assert!( + preserve_error_messages(&source.replace("get() =", "changed ="), &metadata).is_err() + ); + assert!( + preserve_error_messages(&source, &[("missing_name".into(), "Sdk".into())]).is_err() + ); + } fn object(name: &str, asynchronous: bool) -> String { format!( "open class {name}: Disposable, AutoCloseable, {name}Interface\n{{\n override fun destroy() {{ actualFree() }}\n{SHIM}\n internal inline fun <R> callWithHandle(block: (Long) -> R): R {{ actualCall() }}\n override {}fun `close`() {{ actualSourceClose() }}\n}}\n", diff --git a/tools/xtask/src/bin/radroots_ffi_bindgen/main.rs b/tools/xtask/src/bin/radroots_ffi_bindgen/main.rs @@ -4,12 +4,13 @@ use camino::Utf8PathBuf; use clap::{Parser, Subcommand, ValueEnum}; use std::fs; use uniffi_bindgen::bindings::{GenerateOptions, TargetLanguage}; +use uniffi_bindgen::interface::AsType; mod kotlin; mod swift; #[derive(Parser)] -#[command(version = "0.32.2+radroots-native-v1")] +#[command(version = "0.32.2+radroots-native-v2")] struct Cli { #[command(subcommand)] command: Command, @@ -86,7 +87,23 @@ fn main() -> Result<()> { .map(|method| (object.name().to_owned(), method.is_async())) }) .collect(); - if methods.is_empty() { + let mut messages = Vec::new(); + for error in ci + .enum_definitions() + .iter() + .filter(|e| ci.is_name_used_as_error(e.name())) + { + for variant in error.variants() { + if let Some(field) = variant.fields().iter().find(|v| v.name() == "message") { + ensure!( + field.as_type() == uniffi_bindgen::interface::Type::String, + "unsupported native error message type" + ); + messages.push((error.name().to_owned(), variant.name().to_owned())); + } + } + } + if methods.is_empty() && messages.is_empty() { continue; } // This producer has no foreign renaming/package configuration. Fail @@ -94,6 +111,7 @@ fn main() -> Result<()> { let path = stage.join(format!("uniffi/{0}/{0}.kt", ci.namespace())); let original = fs::read_to_string(&path).context("read Kotlin component")?; let generated = kotlin::preserve_close(&original, &methods)?; + let generated = kotlin::preserve_error_messages(&generated, &messages)?; fs::write(path, generated)?; } } diff --git a/tools/xtask/src/sdk_generation/bindings.rs b/tools/xtask/src/sdk_generation/bindings.rs @@ -12,7 +12,8 @@ use crate::{build_control::Mode, sdk_generation::fs::write_or_check}; const FFI_PACKAGE: &str = "radroots_sdk_ffi"; const FFI_VERSION: &str = "0.1.0-alpha"; -const BINDGEN_VERSION: &str = "0.32.2"; +const BINDGEN_VERSION: &str = "0.32.2+radroots-native-v2"; +const BINDGEN: &str = "radroots_ffi_bindgen"; #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] struct SourceLock { @@ -49,7 +50,7 @@ pub fn generate( } let bindgen = target_dir .join("debug") - .join(format!("radroots-sdk-bindgen{}", env::consts::EXE_SUFFIX)); + .join(format!("{BINDGEN}{}", env::consts::EXE_SUFFIX)); if !bindgen.is_file() { return Err(format!( "missing FFI bindgen executable: {}", @@ -58,18 +59,12 @@ pub fn generate( } let temporary = tempfile::tempdir() .map_err(|error| format!("failed to create binding output directory: {error}"))?; + let generated = temporary.path().join("bindings"); let status = Command::new(&bindgen) .args(["generate", "--library"]) .arg(&library) - .args([ - "--crate", - FFI_PACKAGE, - "--language", - language, - "--no-format", - "--out-dir", - ]) - .arg(temporary.path()) + .args(["--language", language, "--no-format", "--out-dir"]) + .arg(&generated) .current_dir(source_root) .status() .map_err(|error| format!("failed to start {}: {error}", bindgen.display()))?; @@ -78,30 +73,27 @@ pub fn generate( "{language} binding generation failed with {status}" )); } - install_outputs(source_root, consumer_root, language, temporary.path(), mode)?; + install_outputs(source_root, consumer_root, language, &generated, mode)?; println!("generated {language} bindings for {FFI_PACKAGE}"); Ok(()) } fn build_bindgen(root: &Path) -> Result<(), String> { let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); - let status = Command::new(cargo) - .args([ - "build", - "--locked", - "-p", - FFI_PACKAGE, - "--lib", - "--bin", - "radroots-sdk-bindgen", - ]) - .current_dir(root) - .status() - .map_err(|error| format!("failed to start Cargo for FFI generation: {error}"))?; - if !status.success() { - return Err(format!( - "FFI library and bindgen build failed with {status}" - )); + for args in [ + vec!["build", "--locked", "-p", FFI_PACKAGE, "--lib"], + vec!["build", "--locked", "-p", "xtask", "--bin", BINDGEN], + ] { + let status = Command::new(&cargo) + .args(args) + .current_dir(root) + .status() + .map_err(|error| format!("failed to start Cargo for FFI generation: {error}"))?; + if !status.success() { + return Err(format!( + "FFI library and bindgen build failed with {status}" + )); + } } Ok(()) } @@ -145,7 +137,7 @@ fn install_outputs( source_package: FFI_PACKAGE.to_owned(), source_version: FFI_VERSION.to_owned(), source_sha256: ffi_source_sha256(source_root)?, - generator: "uniffi".to_owned(), + generator: BINDGEN.to_owned(), generator_version: BINDGEN_VERSION.to_owned(), language: language.to_owned(), outputs, @@ -274,7 +266,7 @@ fn check_language( source_package: FFI_PACKAGE.to_owned(), source_version: FFI_VERSION.to_owned(), source_sha256: ffi_source_sha256(source_root)?, - generator: "uniffi".to_owned(), + generator: BINDGEN.to_owned(), generator_version: BINDGEN_VERSION.to_owned(), language: language.to_owned(), outputs, @@ -292,6 +284,11 @@ fn ffi_source_sha256(root: &Path) -> Result<String, String> { let crate_dir = root.join("crates/sdk_ffi"); let mut paths = vec![crate_dir.join("Cargo.toml"), crate_dir.join("README.md")]; collect_files(&crate_dir.join("src"), &mut paths)?; + paths.push(root.join("tools/xtask/src/sdk_generation/bindings.rs")); + collect_files( + &root.join("tools/xtask/src/bin/radroots_ffi_bindgen"), + &mut paths, + )?; paths.sort(); let mut hasher = Sha256::new(); for path in paths { @@ -335,7 +332,7 @@ mod tests { use crate::build_control::Mode; use super::{ - BINDGEN_VERSION, FFI_PACKAGE, FFI_VERSION, SourceLock, check_generated_language, + BINDGEN, BINDGEN_VERSION, FFI_PACKAGE, FFI_VERSION, SourceLock, check_generated_language, ffi_source_sha256, generate, }; @@ -358,7 +355,7 @@ mod tests { source_package: FFI_PACKAGE.to_owned(), source_version: FFI_VERSION.to_owned(), source_sha256: ffi_source_sha256(&source).expect("FFI source digest"), - generator: "uniffi".to_owned(), + generator: BINDGEN.to_owned(), generator_version: BINDGEN_VERSION.to_owned(), language: "swift".to_owned(), outputs: outputs @@ -390,11 +387,11 @@ mod tests { let expected = BTreeMap::from([ ( "generated/swift/radroots_sdk.swift", - "38ff1a652ff49b45c48601d2b1c0064103c1e815df9e80604f3369af2e53f4ac", + "232932067903afb88fdb6f30714a35ef688b691da23b12ff98c07afdba3a3109", ), ( "generated/swift/radroots_sdkFFI.h", - "2efe02ecda4a68a495bacc61acf8ff41dc84bc01d9132a00b38353a57c51466a", + "03601cc25edbd4d3098460c828a55009b788cbf787864983f974db22db1e47e0", ), ( "generated/swift/radroots_sdkFFI.modulemap", @@ -402,7 +399,7 @@ mod tests { ), ( "generated/kotlin/uniffi/radroots_sdk/radroots_sdk.kt", - "cc57260fade24a3b6d8366f06f17fb2d3132a0293cb61dd2a12d30d95f4a4e66", + "7d7a4955138d226ed0a73bb9070e34c585be4c2d11cc8e9b4f430ccbbebbfc55", ), ]); for (relative, expected_sha256) in expected {