node_workers/
lib.rs

1#![deny(clippy::all)]
2
3//! # Node Workers
4//! This crate lets you call node binaries from Rust code using a pool of workers. This is useful for project that are mostly coded in Rust
5//! but need to leverage Node packages for some tasks, like using Typescript's API or performing SSR with a JS framework.  
6//! Using a pool of workers is fundamental to avoid the cost of booting node binaries on multiple calls.
7//! Medium to big Node binaries can take about a second to bot (or more) depending on its imports, and using a pool of long-lived processes
8//! save you time on subsequent runs. If throughout the usage of your program you need to interact with a node binary multiple times,
9//! a reusable and long-lived process will save you a LOT of time.  
10//!
11//! ## Usage example
12//!
13//! ```rust
14//! use node_workers::WorkerPool;
15//! use serde::Deserialize;
16//! use std::path::Path;
17//! # use std::error::Error;
18//!
19//! #[derive(Deserialize, Debug)]
20//! struct Property {
21//!   pub key: String,
22//!   #[serde(alias = "type")]
23//!   pub propType: String,
24//! }
25//! #[derive(Deserialize, Debug)]
26//! struct Interface {
27//!   pub name: String,
28//!   pub props: Vec<Property>,
29//! }
30//!
31//! # fn main() -> Result<(), Box<dyn Error>> {
32//! // Create a pool of 4 node workers
33//! let mut pool = WorkerPool::setup("examples/worker", 4);
34//! pool.with_debug(true);
35//!
36//! // Payloads
37//! let files = vec![
38//!   Path::new("examples/user-files/user.ts").canonicalize()?,
39//!   Path::new("examples/user-files/pet.ts").canonicalize()?,
40//! ];
41//!
42//! // execute the command "getInterfaces" on every file
43//! // each executed worker will return an array of interfaces (Vec<Interface>)
44//! let interfaces = pool.perform::<Vec<Interface>, _>("getInterfaces", files)?;
45//! let interfaces: Vec<Interface> = interfaces
46//!   .into_iter()
47//!   .map(|x| x.unwrap())
48//!   .flatten()
49//!   .collect();
50//! println!("interfaces: {:#?}", interfaces);
51//! # Ok(())
52//! # }
53//! ```
54
55mod as_payload;
56mod utils;
57mod worker;
58mod worker_pool;
59mod worker_pool_inner;
60mod worker_thread;
61
62pub use as_payload::*;
63pub use worker_pool::*;