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::{bail, Context};
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;
22
23use crate::cli::Cli;
24use crate::db::Db;
25use crate::error::AppState;
26
27/// Validate the CLI config and build the running state + router without
28/// binding the port (so tests can exercise everything up to `serve`).
29pub async fn build_app(cli: &Cli) -> anyhow::Result<(axum::Router, SocketAddr)> {
30 let root = cli
31 .root
32 .canonicalize()
33 .with_context(|| format!("cannot resolve root folder: {}", cli.root.display()))?;
34 if !root.is_dir() {
35 bail!("root folder is not a directory: {}", root.display());
36 }
37
38 let db = Db::open(&cli.db).await?;
39
40 let state = Arc::new(AppState {
41 db,
42 root: root.clone(),
43 https: cli.https,
44 });
45
46 let app = api::router(state).layer(TraceLayer::new_for_http());
47
48 let ip: IpAddr = cli.bind.parse().context("invalid --bind address")?;
49 let addr = SocketAddr::new(ip, cli.port);
50 Ok((app, addr))
51}
52
53/// Parse the CLI, initialize logging and serve until the process is killed.
54pub async fn run() -> anyhow::Result<()> {
55 tracing_subscriber::fmt()
56 .with_env_filter(
57 tracing_subscriber::EnvFilter::try_from_default_env()
58 .unwrap_or_else(|_| "info,tower_http=warn".into()),
59 )
60 .init();
61
62 let cli = Cli::parse();
63 let (app, addr) = build_app(&cli).await?;
64 let listener = tokio::net::TcpListener::bind(addr)
65 .await
66 .with_context(|| format!("cannot bind to {addr}"))?;
67
68 tracing::info!(root = %cli.root.display(), "filebrowser-ng starting");
69 tracing::info!(addr = %addr, "listening (pass --bind 0.0.0.0 to expose beyond localhost)");
70 axum::serve(listener, app).await?;
71 Ok(())
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77 use crate::cli::Cli;
78
79 fn cli(root: &std::path::Path, db: &std::path::Path) -> Cli {
80 Cli {
81 root: root.to_path_buf(),
82 db: db.to_path_buf(),
83 port: 8080,
84 bind: "127.0.0.1".into(),
85 https: false,
86 }
87 }
88
89 #[tokio::test]
90 async fn build_app_ok() {
91 let tmp = tempfile::tempdir().unwrap();
92 std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
93 let c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
94 let (app, addr) = build_app(&c).await.unwrap();
95 let _ = app; // Router built fine
96 assert_eq!(addr.to_string(), "127.0.0.1:8080");
97 }
98
99 #[tokio::test]
100 async fn build_app_missing_root_fails() {
101 let tmp = tempfile::tempdir().unwrap();
102 let c = cli(
103 &tmp.path().join("no-such-root"),
104 &tmp.path().join("db.sqlite"),
105 );
106 assert!(build_app(&c).await.is_err());
107 }
108
109 #[tokio::test]
110 async fn build_app_root_must_be_directory() {
111 let tmp = tempfile::tempdir().unwrap();
112 let file = tmp.path().join("a-file");
113 std::fs::write(&file, "x").unwrap();
114 let c = cli(&file, &tmp.path().join("db.sqlite"));
115 assert!(build_app(&c).await.is_err());
116 }
117
118 #[tokio::test]
119 async fn build_app_rejects_bad_bind() {
120 let tmp = tempfile::tempdir().unwrap();
121 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
122 c.bind = "not-an-ip".into();
123 assert!(build_app(&c).await.is_err());
124 }
125
126 #[tokio::test]
127 async fn build_app_custom_port_bind() {
128 let tmp = tempfile::tempdir().unwrap();
129 let mut c = cli(tmp.path(), &tmp.path().join("db.sqlite"));
130 c.port = 9999;
131 c.bind = "0.0.0.0".into();
132 let (_app, addr) = build_app(&c).await.unwrap();
133 assert_eq!(addr.to_string(), "0.0.0.0:9999");
134 }
135}
136