chdb_rust/runtime.rs
1//! Process-wide engine lifecycle.
2//!
3//! chDB installs signal handlers and starts threads for the whole process, not
4//! for a connection. Both facts are invisible from the connection API and both
5//! matter to a host that has its own signal handling or its own teardown
6//! sequence, so the controls for them live here.
7
8use std::sync::atomic::{AtomicBool, Ordering};
9
10use crate::bindings;
11use crate::error::{Error, Result};
12use crate::registry;
13
14/// Choose whether chDB installs process-wide signal handlers.
15///
16/// May be called at any time, not just before the first connection. Passing
17/// `false` sets a process-wide disable flag *and* immediately resets any
18/// handlers already installed (chDB's own `chdb_set_signal_handlers_enabled`
19/// calls `chdb_reset_signal_handlers` internally when disabling). The flag is
20/// consulted whenever the engine installs handlers — at connect for this
21/// crate's [`Connection`](crate::connection::Connection) API, and at the
22/// start of every query on the one-shot cmdline entry — so a host with an
23/// existing connection can still opt out and have it stick.
24///
25/// Calling this before the first connection is still the cleanest way to
26/// ensure the handlers are never installed at all, since it removes the brief
27/// window where a query could run before the preference is set. But it is no
28/// longer required: this call is infallible and works after connections are
29/// already open.
30///
31/// # Examples
32///
33/// ```no_run
34/// chdb_rust::runtime::signal_handlers(false);
35/// let conn = chdb_rust::connection::Connection::open_in_memory()?;
36/// # Ok::<(), chdb_rust::error::Error>(())
37/// ```
38pub fn signal_handlers(enabled: bool) {
39 // Wraps chdb_set_signal_handlers_enabled. Sets the process-wide disable
40 // flag consulted at handler install; disabling also resets any handlers
41 // already installed, as an immediate effect of this call.
42 unsafe { bindings::chdb_set_signal_handlers_enabled(i32::from(enabled)) };
43}
44
45/// Restore every signal handler chDB installed to `SIG_DFL`.
46///
47/// Does not set the disable flag. Handlers are installed once at connect, not
48/// at the start of every [`Connection::query`](crate::connection::Connection::query),
49/// so a later query on that connection leaves the disposition at `SIG_DFL`. A
50/// later connect may install them again. For an opt-out that also covers a
51/// later connect, use [`signal_handlers`]`(false)`, which sets the flag
52/// consulted at install as well as resetting.
53///
54/// # Examples
55///
56/// ```no_run
57/// let conn = chdb_rust::connection::Connection::open_in_memory()?;
58/// let _ = conn.query("SELECT 1", chdb_rust::format::OutputFormat::TabSeparated)?;
59/// chdb_rust::runtime::reset_signal_handlers();
60/// # Ok::<(), chdb_rust::error::Error>(())
61/// ```
62pub fn reset_signal_handlers() {
63 // Wraps chdb_reset_signal_handlers. Safe at any time; resets disposition
64 // only, does not touch the disable flag.
65 unsafe { bindings::chdb_reset_signal_handlers() };
66}
67
68/// Set once a shutdown has actually succeeded.
69///
70/// A refusal because connections are still open leaves the engine usable, and
71/// this flag correctly stays false for that case — that logic is not changed
72/// here. But per `chdb.h`'s own wording on `chdb_shutdown`, once it starts,
73/// "the library is closed for business for the rest of the process, whether
74/// or not it manages to stop every thread". So a refusal because some thread
75/// could not be stopped still closes the engine, yet leaves this flag unset:
76/// [`ensure_running`] then can't see it, and a later `open()` surfaces the
77/// engine's own `ConnectionFailed` instead of the more informative
78/// [`Error::EngineShutDown`] that flag exists to produce.
79static SHUT_DOWN: AtomicBool = AtomicBool::new(false);
80
81/// Stop the engine, joining every thread chDB started.
82///
83/// Call this before a host teardown sequence of its own — global destructors, a
84/// finalizing language runtime, a sanitizer exit handler — which would
85/// otherwise race the engine's still-running threads.
86///
87/// A plain exit needs care too. Exiting with a connection still open leaves the
88/// engine to be torn down from inside `exit`, and if MergeTree merges are
89/// running in the background at that point the process can crash on its way
90/// out. Drop every connection before the process exits, and call this after the
91/// last one is gone: it returns only once no chDB thread is left. Two common
92/// ways a Rust program keeps a connection open at exit: [`std::process::exit`]
93/// runs no destructors, and a connection held in a `static` is never dropped.
94///
95/// This is one-way. Once it succeeds, no further connection can be opened in
96/// this process. Calling it again is harmless.
97///
98/// # Errors
99///
100/// Returns [`Error::ConnectionsStillOpen`] if any connection is open, and
101/// [`Error::EngineCallFailed`] if the engine could not stop every thread. In the
102/// latter case `chdb.h` documents the engine as closed for the process
103/// regardless — "whether or not it manages to stop every thread" — so this
104/// error means the engine is already shut down even though it is reported as
105/// a failure; the crate's internal shut-down flag is not set for it (see
106/// `SHUT_DOWN`), so a subsequent `open()` will surface `ConnectionFailed`
107/// rather than [`Error::EngineShutDown`].
108///
109/// # Examples
110///
111/// ```no_run
112/// let conn = chdb_rust::connection::Connection::open_in_memory()?;
113/// drop(conn);
114/// chdb_rust::runtime::shutdown()?;
115/// # Ok::<(), chdb_rust::error::Error>(())
116/// ```
117pub fn shutdown() -> Result<()> {
118 if SHUT_DOWN.load(Ordering::SeqCst) {
119 return Ok(());
120 }
121
122 // This count is a snapshot: a connect or drop can race it before
123 // chdb_shutdown below runs. That window only sharpens the error message,
124 // it cannot corrupt state — chdb.h's chdb_shutdown documentation guarantees
125 // it is safe to call concurrently with chdb_connect because callers are
126 // serialized, so a racing connect either gets in first and is counted, or
127 // arrives later and is refused. Worst case here is a less specific error
128 // (falling through to chdb_shutdown's own refusal) rather than this
129 // check's friendlier `ConnectionsStillOpen`.
130 let count = registry::refs();
131 if count != 0 {
132 return Err(Error::ConnectionsStillOpen { count });
133 }
134
135 // Wraps chdb_shutdown. Refuses while the engine holds a connection, which
136 // the check above should already have caught; a refusal here means some
137 // other crate in this process holds one.
138 let state = unsafe { bindings::chdb_shutdown() };
139 if state != bindings::chdb_state_CHDBSuccess {
140 return Err(Error::EngineCallFailed {
141 call: "chdb_shutdown",
142 });
143 }
144
145 SHUT_DOWN.store(true, Ordering::SeqCst);
146 Ok(())
147}
148
149/// Whether a new connection may still be opened.
150pub(crate) fn ensure_running() -> Result<()> {
151 if SHUT_DOWN.load(Ordering::SeqCst) {
152 return Err(Error::EngineShutDown);
153 }
154 Ok(())
155}