1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#![doc = include_str!("../README.md")]

mod sys;

pub use neon;
use neon::event::Channel;
use once_cell::sync::Lazy;
use std::env::current_exe;
use std::ffi::CString;
use std::ops::Deref;
use std::os::raw::c_char;
use std::ptr::null_mut;
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::Mutex;

static CHANNEL_TX_RX: Lazy<(SyncSender<Channel>, Mutex<Receiver<Channel>>)> = Lazy::new(|| {
    let (tx, rx) = sync_channel(0);
    (tx, Mutex::new(rx))
});

#[allow(clippy::unnecessary_wraps)]
mod linked_binding {
    use super::CHANNEL_TX_RX;
    use neon::context::Context;
    use std::sync::Once;

    neon::register_module!(|mut cx| {
        static ONCE: Once = Once::new();
        ONCE.call_once(|| CHANNEL_TX_RX.0.send(cx.channel()).unwrap());
        Ok(())
    });
}

static CHANNEL: Lazy<Channel> = Lazy::new(|| {
    std::thread::spawn(|| {
        const LINKED_BINDING_NAME: &str = "__rust_init";

        unsafe extern "C" fn register_linked_binding(
            raw_env: napi_sys::napi_env,
            raw_exports: napi_sys::napi_value,
        ) -> napi_sys::napi_value {
            linked_binding::napi_register_module_v1(raw_env as _, raw_exports as _) as _
        }
        let mut nm = napi_sys::napi_module {
            nm_version: -1,
            nm_flags: 0,
            nm_filename: concat!(file!(), '\0').as_ptr() as *const c_char,
            nm_register_func: Some(register_linked_binding),
            nm_modname: CString::new(LINKED_BINDING_NAME).unwrap().into_raw(),
            nm_priv: null_mut(),
            reserved: [null_mut(); 4],
        };
        unsafe { napi_sys::napi_module_register(&mut nm) };

        let mut argv0 = current_exe()
            .ok()
            .map(|p| p.to_str().map(str::to_string))
            .flatten()
            .unwrap_or_else(|| "node".to_string())
            + "\0";
        let mut init_code = format!("process._linkedBinding('{}')\0", LINKED_BINDING_NAME);
        let mut option_e = "-e\0".to_string();
        let args = &mut [
            argv0.as_mut_ptr() as *mut c_char,
            option_e.as_mut_ptr() as *mut c_char,
            init_code.as_mut_ptr() as *mut c_char,
        ][..];
        unsafe {
            sys::node_start(args.len() as i32, args.as_mut_ptr());
        }
        panic!("Node.js runtime closed expectedly")
    });
    let channel = CHANNEL_TX_RX.1.lock().unwrap().recv().unwrap();
    channel
});

/// Ensure the Node.js runtime is running and return the channel for queuing tasks into the Node.js event loop.
pub fn channel() -> &'static Channel {
    CHANNEL.deref()
}