lib.rs
⎇
Raw
1//! filebrowser-ng server.
2//!
3//! Library target so the HTTP app can be exercised from integration tests
4//! (via `tower::ServiceExt::oneshot`) without binding a real port. The
5//! `filebrowser-ng` binary is a thin wrapper around [`run`].
6
7use std::net::{IpAddr, SocketAddr};
8use std::sync::Arc;
9
10use anyhow::{Context, bail};
11use clap::Parser;
12use tower_http::trace::TraceLayer;
13
14pub mod api;
15pub mod archive;
16mod assets;
17pub mod auth;
18pub mod cli;
19pub mod db;
20pub mod error;
21pub mod fs;
22pub mod thumb;
23
24use crate::cli::Cli;
25use crate::db::Db;
26use crate::error::AppState;
27
28/// Validate the CLI config and build the running state + router without
29/// binding the port (so tests can exercise everything up to `serve`).
30pub async fn build_app(cli: &Cli) -> anyhow::Result<(axum::Router, SocketAddr)> {
31 let root = cli
32 .root
33 .canonicalize()
34 .with_context(|| format!("cannot resolve root folder: {}", cli.root.display()))?;
35 if !root.is_dir() {
36 bail!("root folder is not a directory: {}", root.display());
37 }
38
39 let db = Db::open(&cli.db).await?;
40
41 let root_name = cli
42 .root_name
43 .clone()
44 .filter(|n| !n.trim().is_empty())
45 .unwrap_or_else(|| root_file_name(&root));
46 let thumbs = match &cli.cache {
47 Some(dir) => Some(Arc::new(
48 crate::thumb::Thumbs::new(dir.clone())
49 .await
50 .with_context(|| format!("cannot use thumbnail cache: {}", dir.display()))?,
51 )),
52 None => None,
53 };
54 if let Some(dir) = cli.cache.clone() {
55 tokio::spawn(crate::thumb::sweep_forever(dir));
56 }
57
58 let state = Arc::new(AppState {
59 db,
60 root: root.clone(),
61 root_name,
62 https: cli.https,
63 public_url: cli
64 .public_url
65 .as_deref()
66 .map(|u| u.trim_end_matches('/').to_string()),
67 thumbs,
68 });
69
70 let app = api::router(state).layer(TraceLayer::new_for_http());
71
72 let ip: IpAddr = cli.bind.parse().context("invalid --bind address")?;
73 let addr = SocketAddr::new(ip, cli.port);
74 Ok((app, addr))
75}
76
77/// Parse the CLI, initialize logging and serve until the process is killed.
78pub async fn run() -> anyhow::Result<()> {
79 tracing_subscriber::fmt()
80 .with_env_filter(
81 tracing_subscriber::EnvFilter::try_from_default_env()
82 .unwrap_or_else(|_| "info,tower_http=warn".into()),
83 )
84 .init();
85
86 let cli = Cli::parse();
87 let (app, addr) = build_app(&cli).await?;
88 let listener = tokio::net::TcpListener::bind(addr)
89 .await
90 .with_context(|| format!("cannot bind to {addr}"))?;
91
92 tracing::info!(root = %cli.root.display(), "filebrowser-ng starting");
93 tracing::info!(addr = %addr, "listening (pass --bind 0.0.0.0 to expose beyond localhost)");
94 axum::serve(listener, app)
95 .with_graceful_shutdown(shutdown_signal())
96 .await?;
97 Ok(())
98}
99
100/// Resolves on Ctrl-C or SIGTERM (what a container runtime sends on stop).
101/// Without this, a restart cuts in-flight uploads and archive downloads
102/// mid-stream instead of letting them finish.
103async fn shutdown_signal() {
104 let ctrl_c = async {
105 let _ = tokio::signal::ctrl_c().await;
106 };
107 #[cfg(unix)]
108 {
109 use tokio::signal::unix::{SignalKind, signal};
110 let mut term = match signal(SignalKind::terminate()) {
111 Ok(s) => s,
112 // No SIGTERM handler: Ctrl-C alone still stops the server.
113 Err(e) => {
114 tracing::warn!(error = %e, "cannot listen for SIGTERM");
115 return ctrl_c.await;
116 }
117 };
118 tokio::select! {
119 () = ctrl_c => {}
120 _ = term.recv() => {}
121 }
122 }
123 #[cfg(not(unix))]
124 ctrl_c.await;
125 tracing::info!("shutting down, waiting for in-flight requests");
126}
127
128/// The root folder's own name; "/" has none, so fall back to the full path.
129pub fn root_file_name(root: &std::path::Path) -> String {
130 root.file_name()
131 .map(|s| s.to_string_lossy().into_owned())
132 .unwrap_or_else(|| root.display().to_string())
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138 use crate::cli::Cli;
139
140 fn cli(root: &std::path::Path, db: &std::path::Path) -> Cli {
141 Cli {
142 root: root.to_path_buf(),
143 db: db.to_path_buf(),
144 root_name: None,
145 port: 8080,
146 bind: "127.0.0.1".into(),
147 cache: None,
148 https: false,
149 public_url: None,
150 }
151 }
152
153 #[tokio::test]
154 async fn build_app_ok() {
155 let tmp = tempfile::tempdir().unwrap();
156 std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
157 let c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
158 let (app, addr) = build_app(&c).await.unwrap();
159 let _ = app; // Router built fine
160 assert_eq!(addr.to_string(), "127.0.0.1:8080");
161 }
162
163 #[tokio::test]
164 async fn build_app_missing_root_fails() {
165 let tmp = tempfile::tempdir().unwrap();
166 let c = cli(
167 &tmp.path().join("no-such-root"),
168 &tmp.path().join("db.sqlite"),
169 );
170 assert!(build_app(&c).await.is_err());
171 }
172
173 #[tokio::test]
174 async fn build_app_root_must_be_directory() {
175 let tmp = tempfile::tempdir().unwrap();
176 let file = tmp.path().join("a-file");
177 std::fs::write(&file, "x").unwrap();
178 let c = cli(&file, &tmp.path().join("db.sqlite"));
179 assert!(build_app(&c).await.is_err());
180 }
181
182 #[tokio::test]
183 async fn build_app_rejects_bad_bind() {
184 let tmp = tempfile::tempdir().unwrap();
185 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
186 c.bind = "not-an-ip".into();
187 assert!(build_app(&c).await.is_err());
188 }
189
190 #[tokio::test]
191 async fn build_app_custom_port_bind() {
192 let tmp = tempfile::tempdir().unwrap();
193 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
194 c.port = 9999;
195 c.bind = "0.0.0.0".into();
196 let (_app, addr) = build_app(&c).await.unwrap();
197 assert_eq!(addr.to_string(), "0.0.0.0:9999");
198 }
199}
200