> ## Documentation Index
> Fetch the complete documentation index at: https://www.orionjs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust Libraries

> Write parts of your app in Rust and call them as async services

Orionjs apps can call Rust in the same process. Each folder in `./rust` is a small library; each one becomes a service you inject like any other. Every exported function returns a Promise and runs on a separate thread pool, so it never blocks the event loop.

You need a Rust toolchain ([rustup](https://rustup.rs)) on the machines that build the app, and `@orion-js/native` in your dependencies.

## Create a library

```bash theme={null}
bun add @orion-js/native
bunx orion rust new file-analyzer
```

This creates:

```
rust/
  Cargo.toml              # generated: links every library into one addon
  file-analyzer/
    Cargo.toml            # this library's own dependencies
    src/lib.rs
app/rust/
  file-analyzer.ts        # generated: FileAnalyzerService + TypeScript types
```

Commit both `rust/` and `app/rust/`. `rust/target` is added to `.gitignore`.

## Write Rust

```rust theme={null}
use orion_native::prelude::*;

#[model]
pub struct Item {
  pub _id: String,
  pub price: f64,
  pub created_at: DateTime,
}

#[export]
pub fn total(items: Vec<Item>) -> Result<f64> {
  if items.is_empty() {
    return Err(NativeError::user("emptyItems", "There are no items to sum"));
  }
  Ok(items.iter().map(|item| item.price).sum())
}
```

* `#[model]` structs become TypeScript interfaces. Field names are camelCased (`created_at` → `createdAt`), `_id` is kept and `Option<T>` fields are optional.
* `#[export]` functions become async functions on the library's service.
* Supported types: `String`, `bool`, `f64`, `f32`, 32-bit and smaller integers, `Option`, `Vec`, `HashMap<String, T>`, `DateTime` (a JS `Date`), `Bytes` (a `Buffer`), and other models. 64-bit integers don't fit in a JS number and are a compile error.

## Use it from TypeScript

```ts theme={null}
import {Inject, Service} from '@orion-js/services'
import {FileAnalyzerService, type Item} from 'app/rust/file-analyzer'

@Service()
export class ReportService {
  @Inject(() => FileAnalyzerService)
  private fileAnalyzer: FileAnalyzerService

  async getTotal(items: Item[]) {
    return await this.fileAnalyzer.total(items)
  }
}
```

## Errors

| Rust | TypeScript |
| - | - |
| `NativeError::user(code, message)` | `UserError` |
| `NativeError::validation([("field", "code")])` | `ValidationError` |
| Input that doesn't match the model | `ValidationError` with the field path, like `items.0.price` |
| A `panic!` or any other error | A rejected promise; the app keeps running |

## Large data

Top-level `Vec<T>` params and returns are sent in small frames, so 100k documents don't pause the event loop. To read many Mongo documents, skip JS decoding entirely and pass raw BSON:

```rust theme={null}
#[export]
pub fn get_stats(examples: RawBsonList<Example>) -> ExampleStats { ... }
```

```ts theme={null}
const docs = await collection.rawCollection.find<Buffer>({}, {raw: true}).toArray()
const stats = await this.exampleStats.getStats(docs)
```

## Libraries using each other

A library can depend on another one in its `Cargo.toml` (`orders = { path = "../orders" }`) and call it directly in Rust. Models are shared too: the generated TypeScript imports them from the other library's file. Model names must be unique across libraries.

## Commands

* `orion dev` compiles `./rust` before starting and rebuilds on changes. A rebuild restarts the app.
* `orion build` compiles in release mode, fails if `app/rust` is out of date, and writes `native.node` next to the bundle. Deploy them together.
* `orion rust build [--release] [--check]` compiles and updates `app/rust`. Use `--check` in CI.
* `orion rust new <name>` creates a library.

All libraries are linked into one addon and share one thread pool (one thread fewer than the number of cores, set with `ORION_NATIVE_THREADS`).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.