Browse Source

feat: add crate feature `notify`

Yujia Qiao 4 years ago
parent
commit
c8e679fa65
2 changed files with 25 additions and 9 deletions
  1. 2 2
      Cargo.toml
  2. 23 7
      src/config_watcher.rs

+ 2 - 2
Cargo.toml

@@ -9,7 +9,7 @@ repository = "https://github.com/rapiz1/rathole"
 readme = "README.md"
 
 [features]
-default = ["tls", "server", "client", "noise"]
+default = ["tls", "server", "client", "noise", "notify"]
 server = []
 client = []
 tls = ["tokio-native-tls"]
@@ -50,4 +50,4 @@ tokio-native-tls = { version = "0.3.0", optional = true }
 async-trait = "0.1.52"
 snowstorm = { git = "https://github.com/black-binary/snowstorm", rev = "1887755", optional = true }
 base64 = { version = "0.13.0", optional = true }
-notify = "5.0.0-pre.13"
+notify = { version = "5.0.0-pre.13", optional = true }

+ 23 - 7
src/config_watcher.rs

@@ -3,7 +3,6 @@ use crate::{
     Config,
 };
 use anyhow::{Context, Result};
-use notify::{event::ModifyKind, EventKind, RecursiveMode, Watcher};
 use std::{
     collections::HashMap,
     path::{Path, PathBuf},
@@ -11,6 +10,9 @@ use std::{
 use tokio::sync::{broadcast, mpsc};
 use tracing::{error, info, instrument};
 
+#[cfg(feature = "notify")]
+use notify::{event::ModifyKind, EventKind, RecursiveMode, Watcher};
+
 #[derive(Debug)]
 pub enum ConfigChangeEvent {
     General(Box<Config>), // Trigger a full restart
@@ -35,6 +37,12 @@ impl ConfigWatcherHandle {
 
         let origin_cfg = Config::from_file(path).await?;
 
+        // Initial start
+        event_tx
+            .send(ConfigChangeEvent::General(Box::new(origin_cfg.clone())))
+            .await
+            .unwrap();
+
         tokio::spawn(config_watcher(
             path.to_owned(),
             shutdown_rx,
@@ -46,6 +54,20 @@ impl ConfigWatcherHandle {
     }
 }
 
+// Fake config watcher when compiling without `notify`
+#[cfg(not(feature = "notify"))]
+async fn config_watcher(
+    _path: PathBuf,
+    mut shutdown_rx: broadcast::Receiver<bool>,
+    _cfg_event_tx: mpsc::Sender<ConfigChangeEvent>,
+    _old: Config,
+) -> Result<()> {
+    // Do nothing except wating for ctrl-c
+    let _ = shutdown_rx.recv().await;
+    Ok(())
+}
+
+#[cfg(feature = "notify")]
 #[instrument(skip(shutdown_rx, cfg_event_tx, old))]
 async fn config_watcher(
     path: PathBuf,
@@ -62,12 +84,6 @@ async fn config_watcher(
         Err(e) => error!("watch error: {:?}", e),
     })?;
 
-    // Initial start
-    cfg_event_tx
-        .send(ConfigChangeEvent::General(Box::new(old.clone())))
-        .await
-        .unwrap();
-
     watcher.watch(&path, RecursiveMode::NonRecursive)?;
     info!("Start watching the config");