@push.rocks/smartrust

A type-safe, standardized bridge between TypeScript and Rust binaries via JSON-over-stdin/stdout IPC.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install 📦

npm install @push.rocks/smartrust
# or
pnpm install @push.rocks/smartrust

Overview 🔭

@push.rocks/smartrust provides a production-ready bridge for TypeScript applications that need to communicate with Rust binaries. It handles the entire lifecycle — binary discovery, process spawning, request/response correlation with timeouts, event streaming, and graceful shutdown — so you can focus on your command definitions instead of IPC plumbing.

Why?

If you're integrating Rust into a Node.js project, you'll inevitably need:

  • A way to find the compiled Rust binary across different environments (dev, CI, production, platform packages)
  • A way to spawn it and establish reliable two-way communication
  • Type-safe request/response patterns with proper error handling
  • Event streaming from Rust to TypeScript
  • Graceful lifecycle management (ready detection, clean shutdown, force kill)

smartrust wraps all of this into two classes: RustBridge and RustBinaryLocator.

Usage 🚀

The IPC Protocol

smartrust uses a simple, newline-delimited JSON protocol over stdin/stdout:

Direction Format Description
TS → Rust (Request) {"id": "req_1", "method": "start", "params": {...}} Command with unique ID
Rust → TS (Response) {"id": "req_1", "success": true, "result": {...}} Response correlated by ID
Rust → TS (Error) {"id": "req_1", "success": false, "error": "msg"} Error correlated by ID
Rust → TS (Event) {"event": "ready", "data": {...}} Unsolicited event (no ID)

Your Rust binary reads JSON lines from stdin and writes JSON lines to stdout. That's it. Stderr is free for logging.

Defining Your Commands

Start by defining a type map of commands your Rust binary supports:

import { RustBridge, type ICommandDefinition } from '@push.rocks/smartrust';

// Define your command types
type TMyCommands = {
  start:      { params: { port: number; host: string }; result: { pid: number } };
  stop:       { params: {};                             result: void };
  getMetrics: { params: {};                             result: { connections: number; uptime: number } };
  reload:     { params: { configPath: string };         result: void };
};

Creating and Using the Bridge

const bridge = new RustBridge<TMyCommands>({
  binaryName: 'my-rust-server',
  envVarName: 'MY_SERVER_BINARY',             // optional: env var override
  platformPackagePrefix: '@myorg/my-server',  // optional: platform npm packages
});

// Spawn the binary and wait for it to signal readiness
const ok = await bridge.spawn();
if (!ok) {
  console.error('Failed to start Rust binary');
  process.exit(1);
}

// Send type-safe commands — params and return types are inferred!
const { pid } = await bridge.sendCommand('start', { port: 8080, host: '0.0.0.0' });
console.log(`Server started with PID ${pid}`);

const metrics = await bridge.sendCommand('getMetrics', {});
console.log(`Active connections: ${metrics.connections}`);

// Listen for events from Rust
bridge.on('management:configChanged', (data) => {
  console.log('Config was changed:', data);
});

// Clean shutdown
bridge.kill();

Binary Locator

The RustBinaryLocator searches for your binary using a priority-ordered strategy:

Priority Source Description
1 binaryPath option Explicit path — skips all other search
2 Environment variable e.g. MY_SERVER_BINARY=/usr/local/bin/server
3 Platform npm package e.g. @myorg/my-server-linux-x64/my-rust-server
4 Local dev paths ./rust/target/release/<name> and ./rust/target/debug/<name>
5 System PATH Standard $PATH lookup

You can also use the locator standalone:

import { RustBinaryLocator } from '@push.rocks/smartrust';

const locator = new RustBinaryLocator({
  binaryName: 'my-rust-server',
  envVarName: 'MY_SERVER_BINARY',
  localPaths: ['/opt/myapp/bin/server'],  // custom search paths
});

const binaryPath = await locator.findBinary();
// Result is cached — call clearCache() to force re-search

Configuration Reference

The RustBridge constructor accepts an IRustBridgeOptions object:

const bridge = new RustBridge<TMyCommands>({
  // --- Binary Locator Options ---
  binaryName: 'my-server',                    // required: name of the binary
  binaryPath: '/explicit/path/to/binary',     // optional: skip search entirely
  envVarName: 'MY_SERVER_BINARY',             // optional: env var for path override
  platformPackagePrefix: '@myorg/my-server',  // optional: platform npm package prefix
  localPaths: ['./build/server'],             // optional: custom local search paths
  searchSystemPath: true,                     // optional: search $PATH (default: true)

  // --- Bridge Options ---
  cliArgs: ['--management'],                  // optional: args passed to binary (default: ['--management'])
  requestTimeoutMs: 30000,                    // optional: per-request timeout (default: 30000)
  readyTimeoutMs: 10000,                      // optional: ready event timeout (default: 10000)
  env: { RUST_LOG: 'debug' },                 // optional: extra env vars for the child process
  readyEventName: 'ready',                    // optional: name of the ready event (default: 'ready')
  logger: myLogger,                           // optional: logger implementing IRustBridgeLogger
});

Events

RustBridge extends EventEmitter and emits the following events:

Event Payload Description
ready Bridge connected and binary reported ready
exit (code, signal) Rust process exited
stderr string A line from the binary's stderr
management:<name> any Custom event from Rust (e.g. management:configChanged)

Custom Logger

Plug in your own logger by implementing the IRustBridgeLogger interface:

import type { IRustBridgeLogger } from '@push.rocks/smartrust';

const logger: IRustBridgeLogger = {
  log(level: string, message: string, data?: Record<string, any>) {
    console.log(`[${level}] ${message}`, data || '');
  },
};

const bridge = new RustBridge<TMyCommands>({
  binaryName: 'my-server',
  logger,
});

Writing the Rust Side

Your Rust binary needs to implement a simple protocol:

  1. On startup, write a ready event to stdout:

    {"event":"ready","data":{"version":"1.0.0"}}\n
    
  2. Read JSON lines from stdin, parse each as {"id": "...", "method": "...", "params": {...}}

  3. Write JSON responses to stdout, each as {"id": "...", "success": true, "result": {...}}\n

  4. Emit events anytime by writing {"event": "name", "data": {...}}\n to stdout

  5. Use stderr for logging — it won't interfere with the IPC protocol

Here's a minimal Rust skeleton:

use serde::{Deserialize, Serialize};
use std::io::{self, BufRead, Write};

#[derive(Deserialize)]
struct Request {
    id: String,
    method: String,
    params: serde_json::Value,
}

#[derive(Serialize)]
struct Response {
    id: String,
    success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

fn main() {
    // Signal ready
    println!(r#"{{"event":"ready","data":{{"version":"1.0.0"}}}}"#);
    io::stdout().flush().unwrap();

    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let line = line.unwrap();
        let req: Request = serde_json::from_str(&line).unwrap();

        let response = match req.method.as_str() {
            "ping" => Response {
                id: req.id,
                success: true,
                result: Some(serde_json::json!({"pong": true})),
                error: None,
            },
            _ => Response {
                id: req.id,
                success: false,
                result: None,
                error: Some(format!("Unknown method: {}", req.method)),
            },
        };

        let json = serde_json::to_string(&response).unwrap();
        println!("{json}");
        io::stdout().flush().unwrap();
    }
}

API Reference 📖

RustBridge<TCommands>

Method / Property Signature Description
constructor new RustBridge<T>(options: IRustBridgeOptions) Create a new bridge instance
spawn() Promise<boolean> Spawn the binary and wait for ready; returns false on failure
sendCommand(method, params) Promise<TCommands[K]['result']> Send a typed command and await the response
kill() void SIGTERM the process, reject pending requests, force SIGKILL after 5s
running boolean Whether the bridge is currently connected

RustBinaryLocator

Method / Property Signature Description
constructor new RustBinaryLocator(options: IBinaryLocatorOptions, logger?) Create a locator instance
findBinary() Promise<string | null> Find the binary using the priority search; result is cached
clearCache() void Clear the cached path to force a fresh search

Exported Interfaces

Interface Description
IRustBridgeOptions Full configuration for RustBridge
IBinaryLocatorOptions Configuration for RustBinaryLocator
IRustBridgeLogger Logger interface: { log(level, message, data?) }
IManagementRequest IPC request shape: { id, method, params }
IManagementResponse IPC response shape: { id, success, result?, error? }
IManagementEvent IPC event shape: { event, data }
ICommandDefinition Single command definition: { params, result }
TCommandMap Record<string, ICommandDefinition>

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

Description
run rust children for performant stuff
Readme 217 KiB
Languages
TypeScript 90%
JavaScript 10%