encore-dev 2.0.0-beta.20

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(|| {
        // Here, where the thread asking is the one to tell by.
        let test_runner = crate::testing::runner_detected();
        // 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(move || build(test_runner)).join())
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
    });
    WATCH.call_once(|| {
        crate::shutdown::watch(core);
        // What a system test's own code does with the app's resources is
        // recorded as the test's, as its calls are.
        if core.system_test().is_some() {
            encore_sdk_core::system_test::set_test_context(crate::testing::outgoing_if_known);
        }
    });
    core
}

/// The core runtime if something has initialized it: for what has nothing
/// to do in a process that never used Encore.
pub(crate) fn initialized() -> Option<&'static CoreRuntime> {
    RUNTIME.get()
}

/// The core runtime when there is one to have: initialized already, or
/// configured by the environment. `None` outside Encore's tooling, where
/// [`core`] would exit, for what works without one.
pub(crate) fn configured() -> Option<&'static CoreRuntime> {
    if RUNTIME.get().is_some() || encore_sdk_core::configured_in_env() {
        Some(core())
    } else {
        None
    }
}

fn build(test_runner: bool) -> CoreRuntime {
    CoreRuntime::builder()
        // A test `cargo test` runs is in test mode without `encore test`.
        .with_test_runner(test_runner)
        // 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 initializes the runtime so an application fails fast at startup rather
/// than on first resource use.
///
/// Calling this is optional; any resource access triggers initialization automatically.
pub fn initialize() {
    core();
    crate::pubsub::start_registered();
}

/// Returns a handle to the core runtime's Tokio runtime, for applications that
/// need to spawn background infrastructure tasks onto it.
pub fn tokio_handle() -> tokio::runtime::Handle {
    core().tokio_handle().clone()
}

/// Blocks the calling thread until a shutdown signal arrives, then drains
/// infrastructure and exits.
///
/// This is the standard way to keep a service process alive when it does not
/// serve incoming requests directly (such as a worker-only service).
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());
}