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 // On a thread of its own: building it starts and stops Tokio runtimes,
18 // which a thread inside one — an async test's, say — must not do.
19 std::thread::scope(|scope| scope.spawn(build).join())
20 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
21 });
22 WATCH.call_once(|| crate::shutdown::watch(core));
23 core
24}
25
26fn build() -> CoreRuntime {
27 CoreRuntime::builder()
28 // In `encore test` / `encore exec` mode (ENCORE_TEST / ENCORE_EXEC
29 // set) these connect to the daemon and supply the config over the
30 // orchestration stream; no-ops otherwise, so the env-var path below
31 // applies as usual.
32 .with_test_mode_from_env()
33 .with_exec_mode_from_env()
34 .with_runtime_config_from_env()
35 .build()
36 .unwrap_or_else(|e| {
37 // Straight to the process's stderr: under `cargo test` the test
38 // harness captures `eprintln!`, and exiting loses what it captured.
39 use std::io::Write;
40 let _ = writeln!(
41 std::io::stderr(),
42 "encore: failed to initialize the SDK runtime: {e:#}"
43 );
44 std::process::exit(1);
45 })
46}
47
48/// Eagerly initialize the runtime, so an app fails fast at startup rather than on
49/// first resource use. Optional — any resource access triggers initialization.
50pub fn initialize() {
51 core();
52 crate::pubsub::start_registered();
53}
54
55/// A handle to the core runtime's tokio runtime, for apps that need to spawn onto
56/// it (e.g. background infra tasks).
57pub fn tokio_handle() -> tokio::runtime::Handle {
58 core().tokio_handle().clone()
59}
60
61/// Block the calling thread until a shutdown signal, then drain infrastructure
62/// and exit. The usual way to keep a service process alive that serves no
63/// requests of its own.
64pub fn run_blocking() {
65 crate::pubsub::start_registered();
66 let handle = tokio_handle();
67 handle.block_on(crate::shutdown::signal());
68 let result = handle.block_on(crate::shutdown::drained());
69 std::process::exit(result.code());
70}