Skip to main content

encore/
runtime.rs

1//! Process-wide access to the initialized `encore_sdk_core` runtime, the native
2//! analogue of the Go SDK's `sdkcore.Get()`. Initialized lazily from the ambient
3//! `ENCORE_*` environment on first use; a failure to initialize is fatal — the
4//! infra core is a hard requirement with no fallback.
5
6use std::sync::{Once, OnceLock};
7
8use encore_sdk_core::Runtime as CoreRuntime;
9
10static RUNTIME: OnceLock<CoreRuntime> = OnceLock::new();
11
12/// The process-wide core runtime, initialized on first use from the environment
13/// (`ENCORE_RUNTIME_CONFIG`, etc.). Linked directly — no FFI.
14pub(crate) fn core() -> &'static CoreRuntime {
15    static WATCH: Once = Once::new();
16    let core = RUNTIME.get_or_init(|| {
17        // Here, where the thread asking is the one to tell by.
18        let test_runner = crate::testing::runner_detected();
19        // On a thread of its own: building it starts and stops Tokio runtimes,
20        // which a thread inside one — an async test's, say — must not do.
21        std::thread::scope(|scope| scope.spawn(move || build(test_runner)).join())
22            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
23    });
24    WATCH.call_once(|| {
25        crate::shutdown::watch(core);
26        // What a system test's own code does with the app's resources is
27        // recorded as the test's, as its calls are.
28        if core.system_test().is_some() {
29            encore_sdk_core::system_test::set_test_context(crate::testing::outgoing_if_known);
30        }
31    });
32    core
33}
34
35/// The core runtime if something has initialized it: for what has nothing
36/// to do in a process that never used Encore.
37pub(crate) fn initialized() -> Option<&'static CoreRuntime> {
38    RUNTIME.get()
39}
40
41/// The core runtime when there is one to have: initialized already, or
42/// configured by the environment. `None` outside Encore's tooling, where
43/// [`core`] would exit, for what works without one.
44pub(crate) fn configured() -> Option<&'static CoreRuntime> {
45    if RUNTIME.get().is_some() || encore_sdk_core::configured_in_env() {
46        Some(core())
47    } else {
48        None
49    }
50}
51
52fn build(test_runner: bool) -> CoreRuntime {
53    CoreRuntime::builder()
54        // A test `cargo test` runs is in test mode without `encore test`.
55        .with_test_runner(test_runner)
56        // In `encore test` / `encore exec` mode (ENCORE_TEST / ENCORE_EXEC
57        // set) these connect to the daemon and supply the config over the
58        // orchestration stream; no-ops otherwise, so the env-var path below
59        // applies as usual.
60        .with_test_mode_from_env()
61        .with_exec_mode_from_env()
62        .with_runtime_config_from_env()
63        .build()
64        .unwrap_or_else(|e| {
65            // Straight to the process's stderr: under `cargo test` the test
66            // harness captures `eprintln!`, and exiting loses what it captured.
67            use std::io::Write;
68            let _ = writeln!(
69                std::io::stderr(),
70                "encore: failed to initialize the SDK runtime: {e:#}"
71            );
72            std::process::exit(1);
73        })
74}
75
76/// Eagerly initializes the runtime so an application fails fast at startup rather
77/// than on first resource use.
78///
79/// Calling this is optional; any resource access triggers initialization automatically.
80pub fn initialize() {
81    core();
82    crate::pubsub::start_registered();
83}
84
85/// Returns a handle to the core runtime's Tokio runtime, for applications that
86/// need to spawn background infrastructure tasks onto it.
87pub fn tokio_handle() -> tokio::runtime::Handle {
88    core().tokio_handle().clone()
89}
90
91/// Blocks the calling thread until a shutdown signal arrives, then drains
92/// infrastructure and exits.
93///
94/// This is the standard way to keep a service process alive when it does not
95/// serve incoming requests directly (such as a worker-only service).
96pub fn run_blocking() {
97    crate::pubsub::start_registered();
98    let handle = tokio_handle();
99    handle.block_on(crate::shutdown::signal());
100    let result = handle.block_on(crate::shutdown::drained());
101    std::process::exit(result.code());
102}