lib

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

qualify.mjs (6988B)


      1 // Actual generated-language execution against the real shared native host.
      2 import { execFileSync, spawnSync } from 'node:child_process';
      3 import { createHash } from 'node:crypto';
      4 import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
      5 import { dirname, join, resolve } from 'node:path';
      6 import { fileURLToPath } from 'node:url';
      7 
      8 const fixture = dirname(fileURLToPath(import.meta.url));
      9 const root = resolve(fixture, '../../../..');
     10 const options = new Map();
     11 for (let index = 2; index < process.argv.length; index += 2) {
     12   const key = process.argv[index], value = process.argv[index + 1];
     13   if (!['--out', '--kotlinc', '--jna', '--java'].includes(key) || !value || options.has(key)) throw new Error('invalid fixture arguments');
     14   options.set(key, resolve(value));
     15 }
     16 if (options.size !== 4 || !process.env.CARGO_TARGET_DIR) throw new Error('requires extbuild and --out/--kotlinc/--jna/--java');
     17 if (process.platform !== 'darwin') throw new Error('this Swift/Kotlin lane requires native macOS');
     18 const out = options.get('--out');
     19 if (existsSync(out)) throw new Error('output directory must be new');
     20 mkdirSync(out, { recursive: true });
     21 const hash = path => createHash('sha256').update(readFileSync(path)).digest('hex');
     22 function files(directory, prefix = '') {
     23   return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
     24     const name = join(prefix, entry.name);
     25     if (entry.isDirectory()) return files(join(directory, entry.name), name);
     26     if (!entry.isFile()) throw new Error('unexpected non-file input');
     27     return [name];
     28   }).sort();
     29 }
     30 const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' });
     31 const head = git('rev-parse', 'HEAD').trim();
     32 const dirty = [...git('diff', '--name-only', '-z', 'HEAD').split('\0'), ...git('ls-files', '--others', '--exclude-standard', '-z').split('\0')].filter(Boolean);
     33 const sourceFiles = [...new Set(['Cargo.toml', 'Cargo.lock', ...dirty, ...files(join(root, 'crates/radroots_ffi')).map(name => `crates/radroots_ffi/${name}`)])].sort().filter(name => existsSync(join(root, name)));
     34 const sources = Object.fromEntries(sourceFiles.map(name => [name, hash(join(root, name))]));
     35 const target = process.env.CARGO_TARGET_DIR;
     36 const library = join(target, 'native_binding_fixture/libradroots_native_binding_fixture.dylib');
     37 const generator = join(target, 'debug/radroots_ffi_bindgen');
     38 const report = { state: 'running', head, dirty_paths: dirty.sort(), started_at: new Date().toISOString(), scope: 'actual native macOS Swift/Kotlin shared-client fixture; no iOS/custody/factory or consumer-adoption qualification', sources, library: { path: library, sha256: hash(library) }, generator: { path: generator, sha256: hash(generator) }, commands: [] };
     39 function persist() { writeFileSync(join(out, 'report.json'), JSON.stringify(report, null, 2) + '\n'); }
     40 function run(command, args, { expectedPanic = false } = {}) {
     41   const started = performance.now();
     42   const result = spawnSync(command, args, { cwd: root, encoding: 'utf8', timeout: 240_000, maxBuffer: 16 * 1024 * 1024 });
     43   const log = join(out, `${report.commands.length}.log`);
     44   writeFileSync(log, (result.stdout || '') + (result.stderr || ''));
     45   const output = readFileSync(log, 'utf8');
     46   const passed = expectedPanic
     47     ? !result.error && ['SIGILL', 'SIGTRAP', 'SIGABRT'].includes(result.signal) && output.includes('synthetic native binding panic probe')
     48     : !result.error && result.status === 0;
     49   report.commands.push({ command: [command, ...args], exit_code: result.status, signal: result.signal, error: result.error?.message, elapsed_seconds: (performance.now() - started) / 1000, log, sha256: hash(log), expected_plain_swift_panic: expectedPanic, passed });
     50   persist();
     51   if (!passed) throw new Error(`native fixture command failed: ${command}\n${output.slice(-6000)}`);
     52   console.log(JSON.stringify({ command, state: 'passed', log }));
     53 }
     54 try {
     55   run(generator, ['--version']);
     56   run('/usr/bin/swiftc', ['--version']);
     57   run(options.get('--kotlinc'), ['-version']);
     58   run(options.get('--java'), ['-version']);
     59   const swift = join(out, 'swift'), kotlin = join(out, 'kotlin');
     60   for (const [language, destination] of [['swift', swift], ['kotlin', kotlin]]) {
     61     run(generator, ['generate', '--library', library, '--language', language, '--no-format', '--out-dir', destination]);
     62     const repeat = destination + '_repeat';
     63     run(generator, ['generate', '--library', library, '--language', language, '--no-format', '--out-dir', repeat]);
     64     const names = files(destination);
     65     if (JSON.stringify(names) !== JSON.stringify(files(repeat)) || names.some(name => hash(join(destination, name)) !== hash(join(repeat, name)))) throw new Error('generation is not byte deterministic');
     66     report[language] = Object.fromEntries(names.map(name => [name, hash(join(destination, name))]));
     67   }
     68   const executable = join(out, 'swift_smoke');
     69   run('/usr/bin/swiftc', ['-swift-version', '6', '-warnings-as-errors', '-parse-as-library', '-I', swift,
     70     ...['radroots_ffi', 'radroots_native_binding_fixture'].flatMap(name => ['-Xcc', `-fmodule-map-file=${join(swift, name + 'FFI.modulemap')}`]),
     71     ...files(swift).filter(name => name.endsWith('.swift')).map(name => join(swift, name)), join(fixture, 'Smoke.swift'), library, '-o', executable]);
     72   run(executable, []);
     73   run('/bin/sh', ['-c', 'ulimit -c 0; exec "$@"', 'native-fixture-panic', executable, '--plain-panic'], { expectedPanic: true });
     74   const coroutine = resolve(options.get('--kotlinc'), '../../lib/kotlinx-coroutines-core-jvm.jar');
     75   report.runtime_jars = Object.fromEntries([options.get('--jna'), coroutine].map(path => [path, hash(path)]));
     76   const classpath = [options.get('--jna'), coroutine].join(':');
     77   const jar = join(out, 'kotlin_smoke.jar');
     78   run(options.get('--kotlinc'), [...files(kotlin).filter(name => name.endsWith('.kt')).map(name => join(kotlin, name)), join(fixture, 'Smoke.kt'), '-Werror', '-classpath', classpath, '-include-runtime', '-d', jar]);
     79   const java = ['-Duniffi.component.radroots_ffi.libraryOverride=' + library, '-Duniffi.component.radroots_native_binding_fixture.libraryOverride=' + library, '-cp', jar + ':' + classpath, 'SmokeKt'];
     80   run(options.get('--java'), java);
     81   run(options.get('--java'), [...java, '--plain-panic']);
     82   const currentDirty = [...git('diff', '--name-only', '-z', 'HEAD').split('\0'), ...git('ls-files', '--others', '--exclude-standard', '-z').split('\0')].filter(Boolean).sort();
     83   if (git('rev-parse', 'HEAD').trim() !== head || JSON.stringify(currentDirty) !== JSON.stringify(report.dirty_paths) || sourceFiles.some(name => !existsSync(join(root, name)) || hash(join(root, name)) !== sources[name]) || hash(library) !== report.library.sha256 || hash(generator) !== report.generator.sha256) throw new Error('qualification inputs changed');
     84   report.state = 'passed';
     85 } catch (error) {
     86   report.state = 'failed'; report.failure = error.message; throw error;
     87 } finally { persist(); }