faucet-server 2.1.0

Welcome to Faucet, your go-to solution for deploying Plumber APIs and Shiny Applications with blazing speed and efficiency. Faucet is a high-performance server built with Rust, offering Round Robin and Round Robin + IP Hash load balancing for seamless scaling and distribution of your R applications. Whether you're a data scientist, developer, or DevOps enthusiast, Faucet streamlines the deployment process, making it easier than ever to manage replicas and balance loads effectively.
Documentation
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::{
    error::{FaucetError, FaucetResult},
    leak,
    networking::get_available_socket,
    server::{
        logging::{parse_faucet_event, FaucetEventResult},
        FaucetServerConfig,
    },
    shutdown::ShutdownSignal,
    telemetry::send_log_event,
};
use std::{
    ffi::OsStr,
    net::SocketAddr,
    path::Path,
    sync::atomic::{AtomicBool, Ordering},
    time::Duration,
};
use tokio::{
    process::Child,
    sync::{Mutex, Notify},
    task::JoinHandle,
};
use tokio_stream::StreamExt;
use tokio_util::codec::{FramedRead, LinesCodec};

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, serde::Deserialize)]
pub enum WorkerType {
    #[serde(alias = "plumber", alias = "Plumber")]
    Plumber,
    #[serde(alias = "shiny", alias = "Shiny")]
    Shiny,
    #[serde(alias = "quarto-shiny", alias = "QuartoShiny", alias = "quarto_shiny")]
    QuartoShiny,
    #[cfg(test)]
    Dummy,
}

fn log_stdio(mut child: Child, target: &'static str) -> FaucetResult<Child> {
    let pid = child.id().expect("Failed to get plumber worker PID");

    let mut stdout = FramedRead::new(
        child.stdout.take().ok_or(FaucetError::Unknown(format!(
            "Unable to take stdout from PID {pid}"
        )))?,
        LinesCodec::new(),
    );

    let mut stderr = FramedRead::new(
        child.stderr.take().ok_or(FaucetError::Unknown(format!(
            "Unable to take stderr from PID {pid}"
        )))?,
        LinesCodec::new(),
    );

    tokio::spawn(async move {
        while let Some(line) = stderr.next().await {
            if let Ok(line) = line {
                match parse_faucet_event(&line) {
                    FaucetEventResult::Output(line) => log::warn!(target: target, "{line}"),
                    FaucetEventResult::Event(e) => {
                        send_log_event(e);
                    }
                    FaucetEventResult::EventError(e) => {
                        log::error!(target: target, "{e:?}")
                    }
                }
            }
        }
    });

    tokio::spawn(async move {
        while let Some(line) = stdout.next().await {
            if let Ok(line) = line {
                log::info!(target: target, "{line}");
            }
        }
    });

    Ok(child)
}

#[derive(Copy, Clone)]
pub struct WorkerConfig {
    pub wtype: WorkerType,
    pub app_dir: Option<&'static str>,
    pub rscript: &'static OsStr,
    pub quarto: &'static OsStr,
    pub workdir: &'static Path,
    pub addr: SocketAddr,
    pub target: &'static str,
    pub worker_id: usize,
    pub worker_route: Option<&'static str>,
    pub is_online: &'static AtomicBool,
    pub qmd: Option<&'static Path>,
    pub handle: &'static Mutex<Option<JoinHandle<FaucetResult<()>>>>,
    pub shutdown: &'static ShutdownSignal,
    pub idle_stop: &'static Notify,
}

impl WorkerConfig {
    fn new(
        worker_id: usize,
        addr: SocketAddr,
        server_config: &FaucetServerConfig,
        shutdown: &'static ShutdownSignal,
    ) -> Self {
        Self {
            addr,
            worker_id,
            is_online: leak!(AtomicBool::new(false)),
            workdir: server_config.workdir,
            worker_route: server_config.route,
            target: leak!(format!("Worker::{}", worker_id)),
            app_dir: server_config.app_dir,
            wtype: server_config.server_type,
            rscript: server_config.rscript,
            quarto: server_config.quarto,
            qmd: server_config.qmd,
            handle: leak!(Mutex::new(None)),
            shutdown,
            idle_stop: leak!(Notify::new()),
        }
    }
    #[allow(dead_code)]
    #[cfg(test)]
    pub fn dummy(target: &'static str, addr: &str, online: bool) -> WorkerConfig {
        WorkerConfig {
            target,
            is_online: leak!(AtomicBool::new(online)),
            addr: addr.parse().unwrap(),
            app_dir: None,
            worker_route: None,
            rscript: OsStr::new(""),
            wtype: WorkerType::Dummy,
            worker_id: 1,
            quarto: OsStr::new(""),
            workdir: Path::new("."),
            qmd: None,
            handle: leak!(Mutex::new(None)),
            shutdown: leak!(ShutdownSignal::new()),
            idle_stop: leak!(Notify::new()),
        }
    }
}

fn spawn_child_rscript_process(
    config: &WorkerConfig,
    command: impl AsRef<str>,
) -> FaucetResult<Child> {
    let mut cmd = tokio::process::Command::new(config.rscript);

    // Set the current directory to the directory containing the entrypoint
    cmd.current_dir(config.workdir)
        .arg("-e")
        .arg(command.as_ref())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .env("FAUCET_WORKER_ID", config.worker_id.to_string())
        // This is needed to make sure the child process is killed when the parent is dropped
        .kill_on_drop(true);

    #[cfg(unix)]
    unsafe {
        cmd.pre_exec(|| {
            // Create a new process group for the child process
            nix::libc::setpgid(0, 0);
            Ok(())
        });
    }

    cmd.spawn().map_err(Into::into)
}

fn spawn_plumber_worker(config: &WorkerConfig) -> FaucetResult<Child> {
    let command = format!(
        r#"
        options("plumber.port" = {port})
        plumber::pr_run(plumber::plumb())
        "#,
        port = config.addr.port()
    );
    let child = spawn_child_rscript_process(config, command)?;

    log_stdio(child, config.target)
}

fn spawn_shiny_worker(config: &WorkerConfig) -> FaucetResult<Child> {
    let command = format!(
        r###"
        options("shiny.port" = {port})
        options(shiny.http.response.filter = function(...) {{
          response <- list(...)[[length(list(...))]]
          if (response$status < 200 || response$status > 300) return(response)
          if ('file' %in% names(response$content)) return(response)
          if (!grepl("^text/html", response$content_type, perl = T)) return(response)
          if (is.raw(response$content)) response$content <- rawToChar(response$content)
          response$content <- sub("</head>", '<script src="__faucet__/reconnect.js"></script></head>', response$content, ignore.case = T)
          return(response)
        }})
        shiny::runApp("{app_dir}")
        "###,
        port = config.addr.port(),
        app_dir = config.app_dir.unwrap_or(".")
    );
    let child = spawn_child_rscript_process(config, command)?;

    log_stdio(child, config.target)
}

fn spawn_quarto_shiny_worker(config: &WorkerConfig) -> FaucetResult<Child> {
    let mut cmd = tokio::process::Command::new(config.quarto);
    // Set the current directory to the directory containing the entrypoint
    cmd.current_dir(config.workdir)
        .arg("serve")
        .args(["--port", config.addr.port().to_string().as_str()])
        .arg(config.qmd.ok_or(FaucetError::MissingArgument("qmd"))?)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .env("FAUCET_WORKER_ID", config.worker_id.to_string())
        // This is needed to make sure the child process is killed when the parent is dropped
        .kill_on_drop(true);

    #[cfg(unix)]
    unsafe {
        cmd.pre_exec(|| {
            // Create a new process group for the child process
            nix::libc::setpgid(0, 0);
            Ok(())
        });
    }

    let child = cmd.spawn()?;

    log_stdio(child, config.target)
}

impl WorkerConfig {
    fn spawn_process(&self) -> FaucetResult<Child> {
        let child_result = match self.wtype {
            WorkerType::Plumber => spawn_plumber_worker(self),
            WorkerType::Shiny => spawn_shiny_worker(self),
            WorkerType::QuartoShiny => spawn_quarto_shiny_worker(self),
            #[cfg(test)]
            WorkerType::Dummy => unreachable!(
                "WorkerType::Dummy should be handled in spawn_worker_task and not reach spawn_process"
            ),
        };

        match child_result {
            Ok(child) => Ok(child),
            Err(e) => {
                log::error!(target: "faucet", "Failed to invoke R for {target}: {e}", target = self.target);
                Err(e)
            }
        }
    }
    pub async fn wait_until_done(&self) {
        if let Some(handle) = self.handle.lock().await.take() {
            log::debug!("Waiting for process to be finished");
            match handle.await {
                Ok(Ok(_)) => {
                    log::debug!("Task ended successfully!")
                }
                Ok(Err(e)) => {
                    panic!("Worker task for target '{}' failed: {:?}", self.target, e);
                }
                Err(e) => {
                    panic!(
                        "Worker task for target '{}' panicked or was cancelled: {:?}",
                        self.target, e
                    );
                }
            }
        }
    }
    pub async fn spawn_worker_task(&'static self) {
        let mut handle = self.handle.lock().await;

        if let Some(handle) = handle.as_ref() {
            if !handle.is_finished() {
                log::warn!(target: "faucet", "Worker task for {target} is already running, skipping spawn", target = self.target);
                return;
            }
        }

        *handle = Some(tokio::spawn(async move {
            #[cfg(test)]
            if self.wtype == WorkerType::Dummy {
                log::debug!(
                    target: "faucet",
                    "Worker {target} is type Dummy, skipping real process spawn.",
                    target = self.target
                );
                return FaucetResult::Ok(());
            }

            'outer: loop {
                let mut child = match self.spawn_process() {
                    Ok(c) => c,
                    Err(e) => {
                        log::error!(
                            target: "faucet",
                            "Worker task for {target} failed to spawn initial process: {e}",
                            target = self.target
                        );
                        return Err(e);
                    }
                };

                let pid = match child.id() {
                    Some(id) => id,
                    None => {
                        let err_msg = format!(
                            "Spawned process for {target} has no PID",
                            target = self.target
                        );
                        log::error!(target: "faucet", "{err_msg}");
                        return Err(FaucetError::Unknown(err_msg));
                    }
                };

                // We will run this loop asynchrnously on this same thread.
                // We will use this to wait for either the stop signal
                // or the child exiting
                let child_loop = async {
                    log::info!(target: "faucet", "Starting process {pid} for {target} on port {port}", port = self.addr.port(), target = self.target);
                    loop {
                        // Try to connect to the socket
                        let check_status = check_if_online(self.addr).await;
                        // If it's online, we can break out of the loop and start serving connections
                        if check_status {
                            log::info!(target: "faucet", "{target} is online and ready to serve connections at {route}", target = self.target, route = self.worker_route.unwrap_or("/"));
                            self.is_online.store(check_status, Ordering::SeqCst);
                            break;
                        }
                        // If it's not online but the child process has exited, we should break out of the loop
                        // and restart the process
                        if child.try_wait()?.is_some() {
                            break;
                        }

                        tokio::time::sleep(RECHECK_INTERVAL).await;
                    }
                    FaucetResult::Ok(child.wait().await?)
                };
                tokio::select! {
                    // If we receive a stop signal that means we will stop the outer loop
                    // and kill the process
                    _ = self.shutdown.wait() => {
                        let _ = child.kill().await;
                        log::info!(target: "faucet", "{target}'s process ({pid}) killed for shutdown", target = self.target);
                        break 'outer;
                    },
                    _ = self.idle_stop.notified() => {
                        self.is_online.store(false, std::sync::atomic::Ordering::SeqCst);
                        let _ = child.kill().await;
                        log::info!(target: "faucet", "{target}'s process ({pid}) killed for idle stop", target = self.target);
                        break 'outer;
                    },
                    // If our child loop stops that means the process crashed. We will restart it
                    status = child_loop => {
                       self
                            .is_online
                            .store(false, std::sync::atomic::Ordering::SeqCst);
                        log::error!(target: "faucet", "{target}'s process ({}) exited with status {}", pid, status?, target = self.target);
                        continue 'outer;
                    }
                }
            }
            log::debug!("{target}'s process has ended.", target = self.target);
            FaucetResult::Ok(())
        }));
    }
}

async fn check_if_online(addr: SocketAddr) -> bool {
    let stream = tokio::net::TcpStream::connect(addr).await;
    stream.is_ok()
}

const RECHECK_INTERVAL: Duration = Duration::from_millis(250);

pub struct WorkerConfigs {
    pub workers: Box<[&'static WorkerConfig]>,
}

const TRIES: usize = 20;

impl WorkerConfigs {
    pub(crate) async fn new(
        server_config: FaucetServerConfig,
        shutdown: &'static ShutdownSignal,
    ) -> FaucetResult<Self> {
        let mut workers =
            Vec::<&'static WorkerConfig>::with_capacity(server_config.n_workers.get());

        for id in 0..server_config.n_workers.get() {
            // Probably hacky but it works. I need to guarantee that ports are never
            // reused
            let socket_addr = 'find_socket: loop {
                let addr_candidate = get_available_socket(TRIES).await?;
                // Check if another worker has already reserved this port
                if workers.iter().any(|w| w.addr == addr_candidate) {
                    continue 'find_socket;
                }
                break 'find_socket addr_candidate;
            };

            let config = leak!(WorkerConfig::new(
                id + 1,
                socket_addr,
                &server_config,
                shutdown
            )) as &'static WorkerConfig;
            workers.push(config);
        }

        let workers = workers.into_boxed_slice();

        Ok(Self { workers })
    }
}