#[cfg(not(target_family = "wasm"))]
use std::cell::Cell;
pub const MAX_DEPTH: usize = 1_000;
pub const STACK_BYTES: usize = 64 << 20;
#[cfg(not(target_family = "wasm"))]
thread_local! {
static ON_ENGINE_STACK: Cell<bool> = const { Cell::new(false) };
}
#[cfg(not(target_family = "wasm"))]
pub fn run<T: Send>(f: impl FnOnce() -> T + Send) -> T {
on_stack(true, f)
}
#[cfg(not(target_family = "wasm"))]
pub fn host<T: Send>(f: impl FnOnce() -> T + Send) -> T {
on_stack(false, f)
}
#[cfg(not(target_family = "wasm"))]
fn on_stack<T: Send>(block_signals: bool, f: impl FnOnce() -> T + Send) -> T {
if ON_ENGINE_STACK.with(Cell::get) {
return f();
}
let mut job = Some(f);
let done = std::thread::scope(|scope| {
let spawned = {
let _blocked = block_signals.then(Signals::block);
std::thread::Builder::new().name("reylo-engine".into()).stack_size(STACK_BYTES).spawn_scoped(scope, || {
ON_ENGINE_STACK.with(|on| on.set(true));
job.take().map(|f| f())
})
};
match spawned {
Ok(thread) => thread.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
Err(_) => None,
}
});
match (done, job) {
(Some(value), _) => value,
(None, Some(f)) => f(),
(None, None) => unreachable!("the engine's thread neither ran nor left its work"),
}
}
#[cfg(target_family = "wasm")]
pub fn run<T: Send>(f: impl FnOnce() -> T + Send) -> T {
f()
}
#[cfg(target_family = "wasm")]
pub fn host<T: Send>(f: impl FnOnce() -> T + Send) -> T {
f()
}
#[cfg(not(target_family = "wasm"))]
struct Signals {
#[cfg(unix)]
old: libc::sigset_t,
}
#[cfg(not(target_family = "wasm"))]
impl Signals {
fn block() -> Signals {
#[cfg(unix)]
unsafe {
let mut all: libc::sigset_t = std::mem::zeroed();
let mut old: libc::sigset_t = std::mem::zeroed();
libc::sigfillset(&mut all);
for fault in [libc::SIGSEGV, libc::SIGBUS, libc::SIGILL, libc::SIGFPE, libc::SIGTRAP, libc::SIGABRT, libc::SIGSYS] {
libc::sigdelset(&mut all, fault);
}
libc::pthread_sigmask(libc::SIG_SETMASK, &all, &mut old);
Signals { old }
}
#[cfg(not(unix))]
Signals {}
}
}
#[cfg(not(target_family = "wasm"))]
impl Drop for Signals {
fn drop(&mut self) {
#[cfg(unix)]
unsafe {
libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut());
}
}
}
#[doc(hidden)]
pub fn nested(shape: &str, n: usize) -> String {
let fold = |start: &str, f: &dyn Fn(String, usize) -> String| (0..n).fold(start.to_string(), |s, i| f(s, i));
match shape {
"sum" => format!("select {} as x from users", vec!["id"; n].join(" + ")),
"concat" => format!("select {} as x from users", vec!["name"; n].join(" || ")),
"and_or" => format!("select id from users where {}", fold("true", &|s, i| format!("id = {i} {} ({s})", if i % 2 == 0 { "or" } else { "and" }))),
"case" => format!("select {} as x from users", fold("0", &|s, i| format!("case when id = {i} then {i} else {s} end"))),
"coalesce" => format!("select {} as x from users", fold("nick", &|s, _| format!("coalesce({s}, name)"))),
"json" => format!("select {} as x from users", fold("id", &|s, _| format!("json_build_object('a', {s})"))),
"subquery" => format!("select ({}) as x from users", fold("select 1", &|s, _| format!("select ({s})"))),
"or" => format!("select id from users where {}", (0..n).map(|i| format!("id = {i}")).collect::<Vec<_>>().join(" or ")),
"parens" => format!("select {}id{} as x from users", "(".repeat(n), ")".repeat(n)),
_ => unreachable!("no shape {shape}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_engine_runs_on_a_thread_of_its_own_once() {
let outer = run(|| (std::thread::current().id(), std::thread::current().name().map(String::from), run(|| std::thread::current().id())));
assert_eq!(outer.1.as_deref(), Some("reylo-engine"));
assert_eq!(outer.0, outer.2);
assert_ne!(outer.0, std::thread::current().id());
}
#[cfg(unix)]
#[test]
fn the_engine_thread_takes_no_signal_meant_for_the_host_and_the_caller_keeps_its_own() {
unsafe fn mask() -> libc::sigset_t {
let mut set: libc::sigset_t = std::mem::zeroed();
libc::pthread_sigmask(libc::SIG_SETMASK, std::ptr::null(), &mut set);
set
}
let before = unsafe { mask() };
let inside = run(|| unsafe {
let set = mask();
[libc::SIGINT, libc::SIGTERM, libc::SIGUSR1, libc::SIGSEGV, libc::SIGBUS].map(|s| libc::sigismember(&set, s) == 1)
});
assert_eq!(inside, [true, true, true, false, false]);
let hosted = host(|| unsafe { libc::sigismember(&mask(), libc::SIGTERM) == 1 });
assert_eq!(hosted, unsafe { libc::sigismember(&before, libc::SIGTERM) == 1 });
let after = unsafe { mask() };
assert_eq!(unsafe { libc::sigismember(&before, libc::SIGINT) }, unsafe { libc::sigismember(&after, libc::SIGINT) });
}
}