Open Enterprise
Browse topics
DocumentationApplication integration

Embed the Rust runtime

Open Enterprise can run inside a Rust application as a library. The application and the enterprise runtime share one Tokio process and one Axum listener. PostgreSQL remains a separate dependency.

The supported host API is enterprise_runtime::embedding. Runtime::start initializes providers and starts all required background workers. The standalone executable uses the same worker implementation. The host owns listeners, signal handlers, global tracing, application state, and request shutdown.

Start a host

  1. Add enterprise-runtime from this workspace or a pinned repository revision to the host dependencies.
  2. Add compatible Axum 0.8, Tokio 1, and Tower 0.5 dependencies.
  3. Load the runtime configuration with enterprise_runtime::config::Config::load.
  4. Await Runtime::start before the host accepts enterprise requests.
  5. Merge runtime.routes() into the root Axum router.
  6. Keep the runtime owner alive until the host stops.

The compiled example (crates/enterprise-runtime/examples/embedded.rs) includes authorization, route composition, failure supervision, and bounded shutdown. The example instructions (examples/rust-embedding/README.md) include a minimal configuration without external identity providers.

Rust
use axum::{Router, routing::get};
use enterprise_runtime::{config::Config, embedding::Runtime};

let enterprise = Runtime::start(Config::load("enterprise.yaml")?).await?;
let app = Router::new()
    .route("/app-api/version", get(|| async { "1" }))
    .merge(enterprise.routes())
    .fallback(|| async { (axum::http::StatusCode::NOT_FOUND, "Application page not found") });
// Keep `enterprise` alive while the host serves `app`.
enterprise.shutdown().await?;

Startup makes one attempt and returns typed configuration, storage, or provider errors. The host controls retries and an overall startup deadline. Runtime::start_with_progress reports the initialization phase through an inline callback. The callback must not block. Initialization failure starts no enterprise workers.

Own the route paths

The runtime uses paths at the origin root. server.public_url names the external origin, such as https://changes.example.com. The host must reserve the runtime paths:

Paths Owner
/v1/*, /scim/*, /openapi.json Enterprise API and provisioning
/auth/*, /account, /account/* Login callbacks and local account pages
/admin, /admin/* Enterprise administration and static console assets
/.well-known/*, /oauth/* Configured OAuth issuer and discovery
/healthz, /readyz Enterprise liveness and readiness
/app-api/* Product routes in the example

The configured issuer can add its own protocol paths. The generated OpenAPI document and the configured issuer metadata describe the exact enabled endpoints. Arbitrary nesting under a prefix such as /enterprise is unsupported. Redirects, metadata, and cookies retain their root paths. Axum rejects duplicate route paths and methods during composition.

Runtime::routes has no custom fallback, so the host can keep its own fallback. Unmatched paths use that fallback, including unknown paths under /v1. Runtime::router includes the standard enterprise JSON fallback for a dedicated listener or in-process requests. Enterprise authentication, body limits, timeouts, request correlation, and response policies remain on enterprise routes. The host applies its own middleware to product routes.

The host must use into_make_service_with_connect_info::<SocketAddr>() to preserve peer addresses for local authentication limits. Proxy deployments use server.trusted_proxies to identify trusted forwarded addresses. The example includes this listener configuration.

Administration assets remain a separate build artifact. npm run build builds the static console. ENTERPRISE_ADMIN_ASSETS_DIR selects its directory, which defaults to apps/console/dist. Embedding the Rust runtime does not embed these files in the binary. The React embedding guide covers product-owned administration panels.

Authorize product actions

runtime.access() returns a clonable Access adapter for host handlers. Access::authorize(headers, organization, action) authenticates the caller and checks the current organization-level authority. The adapter uses existing session revocation, service scopes, portal delegation, and browser origin/CSRF checks. Every call checks current authority instead of trusting a cached principal.

Rust
let caller = access.authorize(headers, "org_demo", "change:approve").await?;
// Enforce the product's reviewer, request-version, and transaction rules here.

User actions can use custom role permissions such as change:approve. Service credentials retain the runtime's configured scope vocabulary. A service key with authorization:check does not grant every product action. Portal credentials retain their delegated operation limits. The host passes the original headers unchanged. The local account cookie alone does not authenticate a product API request.

For cookie sessions that belong to the product, the host checks its own CSRF protection before it forwards an enterprise bearer credential. The runtime cannot check a product cookie that the host converts into an authorization header.

Access::authorize checks organization-level authority without a resource. The host must enforce resource permissions, independent approval, immutable request versions, and transaction-time checks for sensitive product operations. The host must also record its own business audit events. Authorization does not make a later product write part of an enterprise transaction.

Other enterprise operations can use the existing HTTP API without a network hop:

Rust
use tower::ServiceExt;

let response = runtime.router().oneshot(
    Request::builder()
        .uri("/v1/capabilities")
        .header("authorization", format!("Bearer {token}"))
        .body(Body::empty())?,
).await?;

These requests retain the normal handlers, credential checks, validation, and audit behavior. Provider and AppState internals are lower-level implementation details. Direct provider calls do not automatically apply the runtime's request authorization.

Supervise and stop workers

The runtime starts event and email workers only for configured capabilities. Maintenance covers administration reconciliation, permission synchronization, and security signals. Cleanup covers sessions, local accounts, issuer keys, administration upkeep, and retention. Provider errors keep their existing retry behavior and metrics.

The host lifecycle has four required steps:

  1. Select on runtime.failure() alongside host termination and listener completion.
  2. Stop ingress after a worker failure or host termination.
  3. Drain host requests and await runtime.shutdown() within the host shutdown deadline.
  4. Release router and access clones after shutdown to release their database pools.

failure() reports unexpected task exits, cancellation, or panics. The failure future is cancellation-safe. Worker failure marks enterprise routes unavailable and signals the other workers to stop. /healthz remains live, while /readyz and other enterprise routes return 503. Access adapters also reject calls after stop or worker failure.

Shutdown lets in-flight worker iterations finish within server.shutdown_grace_seconds. After that deadline, shutdown aborts the task tree and returns ShutdownError::TimedOut. Dropping the runtime or cancelling its shutdown future also aborts its task tree. Task abortion depends on Tokio scheduling, so host code must not block executor threads. The runtime does not stop host listeners or drain host requests.

runtime.metrics_router() exposes /metrics for a listener that the host chooses. Metrics are process-wide, while oe_ready reflects this runtime owner's worker health. The library installs no signal handlers or global telemetry subscriber. server.host, server.port, and server.metrics_port do not create listeners through Runtime::start. They remain subject to configuration validation and serve as listener values in the example.

Own enterprise storage

Enterprise storage uses its own PostgreSQL pool. A dedicated database and database role isolate enterprise tables from product tables. The same PostgreSQL server can host both databases. storage.max_connections limits the enterprise pool independently of the product pool.

storage.migrate_on_startup: true lets initialization apply pending enterprise migrations. With false, initialization requires a current schema and returns an error for pending migrations. A deployment migration job can run enterprise-runtime migrate with a separate migration role. The host never passes its product pool or transaction to the runtime.

A PostgreSQL change-approval product has three separate boundaries: product storage, enterprise storage, and each target database. An approved SQL execution and an enterprise audit event do not share an atomic transaction. The product needs durable execution receipts, an outbox, and reconciliation for uncertain outcomes.

Search documentation