> ## 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.

# Orion v5

> Rust becomes the host: move routes, jobs and echoes to Rust one at a time

In v5 a Rust binary can be the process that runs your app. It owns the public port, claims the
jobs, and consumes the events. Routes, jobs, and echoes declared in Rust run in Rust; everything
else goes to your Orionjs app, which runs as a worker behind a private unix socket. Move a
controller to Rust and it stops reaching Node, with no other change.

```
            ┌──────────────── Rust host (orionrs) ───────────────┐
 HTTP  ───► │ Rust routes        → handled here                  │
            │ everything else    → proxied to Node ───────────┐  │
 Mongo ◄──► │ job scheduler      → Rust jobs here, JS jobs ───┤  │
 Pulse ◄──► │ event consumer     → Rust echoes here, JS ones ─┤  │
            └─────────────────────────────────────────────────┼──┘
                                                              ▼
                                        Orionjs app (Node), unix socket
```

Without the host, v5 apps run like v4 apps. The host is opt-in.

> [!NOTE]
>
> Upgrading an existing v4 project? See [Upgrading to v5](https://www.orionjs.com/guides/upgrading-to-v5.md). If you want to
> keep Node or Bun as the host and call Rust functions for CPU-heavy work instead, see
> [Rust Libraries](https://www.orionjs.com/guides/rust.md).

## Breaking changes

* **Echoes: Kafka was removed.** [Pulse](https://www.orionjs.com/overview/other-modules/pulse/introduction.md) is the only
  event transport, configured as before in `events.pulse`:

  ```ts theme={null}
  await startService({
    echoes,
    requests: {key: env.echoes_password, services},
    events: {pulse: {connectionString: env.mongo_url, consumerGroup: 'my-service'}},
  })
  ```

  Top-level `client`, `producer`, and `consumer`, `events.kafka`, `events.consumeFrom`,
  `events.publishTo`, and `onMessage` are gone, and `publish()` no longer takes `acks` / `timeout`.
  Request echoes (`/echoes-services`) keep the same wire format, so v4 and v5 services can call
  each other.

Everything else is compatible with v4: same collections, same job and event protocols. v4 workers
and v5 hosts can share jobs and Pulse consumer groups during a rolling deploy.

## The Rust host

All crates are version `5.0.0`, target Rust edition 2024 (Rust `1.88+`), and live in
[`crates/`](https://github.com/orionjs/orionjs/tree/master/crates):

| Crate | What it does |
| - | - |
| `orionrs` | The host: `App`, axum routes, JWT extractor, env loader, re-exports the other crates |
| `orionrs-core` | Shared `Error` / `Result` types and the Node worker process, socket, and HTTP proxy |
| `orionrs-jobs` | Jobs scheduler and runner, compatible with `@orion-js/dogs` |
| `orionrs-echoes` | Echoes (events and requests), compatible with `@orion-js/echoes` |
| `orionrs-pulse` | A Rust port of `@orion-js/pulse` |
| `orionrs-mongo` | A thin layer over the official MongoDB driver: connections, IDs, BSON/JSON dates |
| `orionrs-env` | Reads the encrypted `orion-env` YAML file |

The host is built on [tokio](https://tokio.rs) (the async runtime), [tower](https://docs.rs/tower)
(middleware), and [axum](https://docs.rs/axum) (the web framework).

Add a `server/` crate next to your app:

```toml theme={null}
# server/Cargo.toml
[package]
name = "my-app-server"
version = "0.1.0"
edition = "2024"
rust-version = "1.88"

[dependencies]
orionrs = "5"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

```rust theme={null}
// server/src/main.rs
use orionrs::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    App::new()
        .routes(Router::new().route("/hello", get(|| async { "Hello from Rust" })))
        .node(Node::command("node build/index.js"))
        .run()
        .await?;
    Ok(())
}
```

Run it from the app's folder with the same env vars as the app (`ORION_ENV_FILE_PATH`,
`ORION_ENV_SECRET_KEY`). It listens on `http_port` / `PORT` (default `3000`) and starts the app with
`ORION_HOST=rust`, a private unix socket (`ORION_HOST_SOCKET`), and a per-process secret token
(`ORION_HOST_TOKEN`). The app keeps running its own jobs and event consumers until you give the host
`.jobs(...)` or `.echoes(...)` (with `.pulse(...)`); from then on the host runs them.

In development, override the worker command with `ORION_NODE_COMMAND` so the host runs `orion dev`
instead of the built bundle:

```bash theme={null}
ORION_NODE_COMMAND="bunx orion dev" cargo run --manifest-path server/Cargo.toml
```

`orion dev` restarts the worker on every change; the host keeps the port open and requests wait
until the worker is back.

On `SIGTERM` or `SIGINT`, the host stops taking new requests, jobs, and events, waits for what is
running (in Rust and in Node), and then stops the worker's process group (`SIGTERM`, then `SIGKILL`
after 10 seconds). If the worker exits by itself, the host exits with an error so your orchestrator
restarts both.

### Routes

Rust routes are plain [axum](https://docs.rs/axum) routes. Unmatched paths—and unmatched HTTP
methods on a path handled by Rust—are forwarded to the Orionjs app, so you can move `GET /items` to
Rust while `POST /items` stays in JS.

Errors answer with the same JSON shape as `@orion-js/http`, so clients can't tell where a route
runs:

```rust theme={null}
use orionrs::mongo::bson::doc;
use orionrs::mongo::mongodb::Collection;
use orionrs::prelude::*;

async fn get_example(
    State(examples): State<Collection<Example>>,
    Path(id): Path<String>,
) -> Result<Json<Example>> {
    let example = examples
        .find_one(doc! {"_id": &id})
        .await?
        .ok_or_else(|| Error::user("notFound", "Example not found"))?;
    Ok(Json(example))
}
```

* `Error::user(code, message)` and `Error::user_with_extra(code, message, extra)` answer `400`
  (`UserError` JSON).
* `Error::validation(errors)` answers `400` (`ValidationError` JSON).
* `Error::auth(message)` answers `401` (`AuthError` JSON).
* `Error::internal(message)` and any `std::error::Error` converted with `?` answer `500` with the
  same 10-character SHA-1 hash as `@orion-js/http` (while logging the underlying message).

The `Jwt<Claims>` extractor validates `Authorization: Bearer <token>` headers using `jwt_secret` /
`JWT_SECRET` (HS256) automatically from the env file, or a custom `JwtConfig` passed via
`App::jwt(...)` (`JwtConfig::hs256` or `JwtConfig::new` for RS256, issuer/audience validation,
etc.). Use `Option<Jwt<Claims>>` when authentication is optional (missing tokens become `None`;
invalid tokens still return `401`).

### MongoDB and env

`orionrs::env()` loads the app's encrypted env file once (`ORION_ENV_FILE_PATH` +
`ORION_ENV_SECRET_KEY`). `orionrs::mongo` connects with the official `mongodb` driver and provides
Orionjs-compatible IDs and dates:

```rust theme={null}
use orionrs::mongo;
use orionrs::mongo::bson::DateTime;
use serde::{Deserialize, Serialize};

let db = mongo::connect(env()).await?;
// Named connection: mongo_url_analytics / MONGO_URL_ANALYTICS
// let analytics_db = mongo::connect_named(env(), "analytics").await?;

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Example {
    #[serde(rename = "_id")]
    pub id: String,
    pub name: String,
    #[serde(with = "orionrs::mongo::date")]
    pub created_at: DateTime,
    #[serde(default, skip_serializing_if = "Option::is_none", with = "orionrs::mongo::date::option")]
    pub processed_at: Option<DateTime>,
}

let id = mongo::typed_id("ex"); // "ex-<uuidv7>", same as typedId('ex')
let random = mongo::random_id(); // 17-char ID, same as generateId()
```

### Jobs

With `.jobs(...)`, the host schedules every job from `orionjs.jobs_dogs_records` and
`orionjs.jobs_dogs_history`. Jobs defined in Rust run in Rust; jobs defined only in the app are
claimed by the host and run in Node, keeping their JS `onError`, `onStale`, `getNextRun`,
`executionGuard`, `canTakeJobs`, `getJobsFilter`, and `maxParallelExecutionsPerServer`. Call
`startWorkers` in the app as before: with the host it registers the jobs instead of polling.

```rust theme={null}
use std::time::Duration;
use orionrs::jobs::JobsConfig;
use orionrs::prelude::*;
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct SendEmail {
    to: String,
}

let jobs = Jobs::new(db.clone())
    .with_config(JobsConfig {
        workers_count: 4,
        n_partitions: 1, // Must match nPartitions in JS startWorkers()
        ..Default::default()
    })
    .job(RecurrentJob::every("createExamples", Duration::from_secs(60), |_context| async {
        Ok(())
    }))
    .job(
        RecurrentJob::cron("dailyReport", "0 9 * * *", "America/Santiago", |_context| async {
            Ok(())
        })?,
    )
    .job(
        EventJob::new("sendEmail", |params: SendEmail, _context: JobContext| async move {
            tracing::info!(to = params.to, "Sending email");
            Ok(())
        })
        .max_tries(5)
        .max_parallel_executions(2),
    );

let scheduler = jobs.scheduler();
App::new().jobs(jobs) // ...

// Schedule from Rust, including jobs that still run in Node:
scheduler
    .schedule_named("processExample", json!({"exampleId": id}), ScheduleOptions::new())
    .await?;
```

Events scheduled from JS with `job.schedule()` or from Rust with `scheduler.schedule(...)`,
`scheduler.schedule_named(...)`, or `scheduler.schedule_many(...)` run wherever the job is defined.
A job defined in both runs in Rust. Long-running Rust jobs can renew their lock with
`context.extend_lock_time(duration).await` and check `context.is_stale()`.

### Echoes

With `.echoes(...)`, the host answers `POST /echoes-services` and—when `.pulse(...)` is
configured—consumes all Pulse events. Echoes defined in Rust run in Rust; the rest are delivered to
the app through `echoes.deliver` with the same retries and dead letters. If you omit `.pulse(...)`,
the host handles Rust request echoes and forwards other requests while the app keeps consuming its
own Pulse events.

```rust theme={null}
use orionrs::prelude::*;
use orionrs::pulse::ConnectOptions;
use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ExampleProcessed {
    example_id: String,
}

#[derive(Deserialize)]
struct CountExamples {
    name: Option<String>,
}

#[derive(Serialize)]
struct ExamplesCount {
    count: u64,
}

let echoes = Echoes::new()
    .pulse(ConnectOptions::new(db.clone(), "my-service"))
    .event("example.processed", |params: ExampleProcessed, _context: EventContext| async move {
        tracing::info!(example_id = params.example_id, "Processed");
        Ok(())
    })
    .request("countExamples", |params: CountExamples| async move {
        let _ = params.name;
        Ok(ExamplesCount { count: 0 })
    });

let publisher = echoes.publisher();
App::new().echoes(echoes) // ...

publisher.publish("example.created", json!({"exampleId": id})).await?;
```

Use the same `consumerGroup` as the app. The requests password is read from `echoes_password` /
`ECHOES_PASSWORD` (or set explicitly with `.password(...)`), and the handler path defaults to
`/echoes-services` (override with `.handler_path(...)`). For batch consumers matching
`createEchoBatchEvent` in JS, use `.batch_event(topic, batch_size, EventOptions::default(), handler)`.

## A full example

[`examples/backend-base`](https://github.com/orionjs/orionjs/tree/master/examples/backend-base)
runs a flow across both languages: a Rust route (`POST /examples`) publishes `example.created`, a
JS echo schedules the JS job `processExample`, the host claims and runs it in Node, and it publishes
`example.processed`, which a Rust echo handles. Its end-to-end tests (`bun run e2e`) start the real
host binary and Orionjs app.


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