encore-dev 2.0.0-beta.5

Rust SDK for Encore applications
Documentation
//! Process-wide access to the initialized `encore_sdk_core` runtime, the native
//! analogue of the Go SDK's `sdkcore.Get()`. Initialized lazily from the ambient
//! `ENCORE_*` environment on first use; a failure to initialize is fatal — the
//! infra core is a hard requirement with no fallback.

use std::sync::{Once, OnceLock};

use encore_sdk_core::Runtime as CoreRuntime;

static RUNTIME: OnceLock<CoreRuntime> = OnceLock::new();

/// The process-wide core runtime, initialized on first use from the environment
/// (`ENCORE_RUNTIME_CONFIG`, etc.). Linked directly — no FFI.
pub(crate) fn core() -> &'static CoreRuntime {
    static WATCH: Once = Once::new();
    let core = RUNTIME.get_or_init(|| {
        // On a thread of its own: building it starts and stops Tokio runtimes,
        // which a thread inside one — an async test's, say — must not do.
        std::thread::scope(|scope| scope.spawn(build).join())
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
    });
    WATCH.call_once(|| crate::shutdown::watch(core));
    core
}

fn build() -> CoreRuntime {
    CoreRuntime::builder()
        // In `encore test` / `encore exec` mode (ENCORE_TEST / ENCORE_EXEC
        // set) these connect to the daemon and supply the config over the
        // orchestration stream; no-ops otherwise, so the env-var path below
        // applies as usual.
        .with_test_mode_from_env()
        .with_exec_mode_from_env()
        .with_runtime_config_from_env()
        .build()
        .unwrap_or_else(|e| {
            // Straight to the process's stderr: under `cargo test` the test
            // harness captures `eprintln!`, and exiting loses what it captured.
            use std::io::Write;
            let _ = writeln!(
                std::io::stderr(),
                "encore: failed to initialize the SDK runtime: {e:#}"
            );
            std::process::exit(1);
        })
}

/// Eagerly initialize the runtime, so an app fails fast at startup rather than on
/// first resource use. Optional — any resource access triggers initialization.
pub fn initialize() {
    core();
    crate::pubsub::start_registered();
}

/// A handle to the core runtime's tokio runtime, for apps that need to spawn onto
/// it (e.g. background infra tasks).
pub fn tokio_handle() -> tokio::runtime::Handle {
    core().tokio_handle().clone()
}

/// Block the calling thread until a shutdown signal, then drain infrastructure
/// and exit. The usual way to keep a service process alive that serves no
/// requests of its own.
pub fn run_blocking() {
    crate::pubsub::start_registered();
    let handle = tokio_handle();
    handle.block_on(crate::shutdown::signal());
    let result = handle.block_on(crate::shutdown::drained());
    std::process::exit(result.code());
}