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 initialize the runtime, so an app fails fast at startup rather than on
77/// first resource use. Optional — any resource access triggers initialization.
78pub fn initialize() {
79    core();
80    crate::pubsub::start_registered();
81}
82
83/// A handle to the core runtime's tokio runtime, for apps that need to spawn onto
84/// it (e.g. background infra tasks).
85pub fn tokio_handle() -> tokio::runtime::Handle {
86    core().tokio_handle().clone()
87}
88
89/// Block the calling thread until a shutdown signal, then drain infrastructure
90/// and exit. The usual way to keep a service process alive that serves no
91/// requests of its own.
92pub fn run_blocking() {
93    crate::pubsub::start_registered();
94    let handle = tokio_handle();
95    handle.block_on(crate::shutdown::signal());
96    let result = handle.block_on(crate::shutdown::drained());
97    std::process::exit(result.code());
98}