basic echo HTTP server

This commit is contained in:
jfmonty2 committed 2026-11-22 06:14:06 -05:00
1 parent c86a898879
commit d976eebbbc
11 files changed
+151 -45

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
[env]
# in development (i.e. when running through Cargo), store state in project directory
CREDDY_DATA_DIR = { value = "data", relative = true }
CREDDY_RUNTIME_DIR = { value = "data", relative = true }
Generated
+16 -1
View File
@@ -1445,12 +1445,14 @@ dependencies = [
"hyper-util",
"include_dir",
"jiff",
"rustix",
"serde",
"serde_json",
"smol",
"smol-hyper",
"tempfile",
"testresult",
"thiserror 2.0.21",
"tokio",
"uuid",
]
@@ -7040,6 +7042,19 @@ dependencies = [
"futures-lite",
]
[[package]]
name = "smol-hyper"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7428a49d323867702cd12b97b08a6b0104f39ec13b49117911f101271321bc1a"
dependencies = [
"async-executor",
"async-io",
"futures-io",
"hyper",
"pin-project-lite",
]
[[package]]
name = "smol_str"
version = "0.3.7"
+3 -1
View File
@@ -21,11 +21,13 @@ hyper = { version = "1.12.0", features = ["server", "http1"] }
hyper-util = { version = "0.1.21", features = ["tokio"] }
include_dir = "0.7.4"
jiff = { version = "1.0.1", features = ["serde"] }
rustix = { version = "1.1.6", features = ["net"] }
serde = "1.0.229"
serde_json = "1.0.154"
smol = "2.0.2"
smol-hyper = "0.1.1"
testresult = "0.4.2"
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] }
uuid = { version = "1.29.3", features = ["v4", "serde"] }
[dev-dependencies]
+6
View File
@@ -7,6 +7,7 @@ use gpui_omarchy::ActiveTheme;
use crate::config::AppConfig;
use crate::screens::{CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen};
use crate::session::AppSession;
use crate::srv;
pub struct CreddyApp {}
@@ -44,7 +45,12 @@ impl Render for CreddyApp {
/// Install the globals and open the main window. Tests call this too, so they get the same wiring.
pub fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle<CreddyApp> {
// todo: `SetupError` global, that gets populated if any of the fallible setup fails so we can display it in the UI
gpui_omarchy::init(cx);
srv::start_creddy_server(&config.creddy_server_addr(), cx.to_async())
.expect("Failed to start server, we will add proper error handling for this later");
cx.set_global(config);
cx.set_global(session);
cx.set_global(Screen::Home);
+38 -39
View File
@@ -42,7 +42,7 @@ impl PublicConfig {
}
}
/// Config that can be stored in the encrypted db
/// Config that should be stored in the encrypted db
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivateConfig {
@@ -60,6 +60,7 @@ impl Default for PrivateConfig {
#[derive(Debug, Clone)]
pub struct AppConfig {
pub data_dir: PathBuf,
pub runtime_dir: PathBuf,
pub db_salt: [u8; 32],
pub rehide_ms: u64,
}
@@ -67,31 +68,35 @@ pub struct AppConfig {
impl AppConfig {
/// Load config from disk, using defaults for non-public values.
pub fn load() -> Result<AppConfig, CreddyError> {
let data_dir = AppConfig::resolve_data_dir(
env::var_os("CREDDY_DATA_DIR"),
dirs::data_dir(),
)?;
let data_dir = env::var_os("CREDDY_DATA_DIR")
.map(PathBuf::from)
.or_else(|| dirs::data_dir().map(|d| d.join("creddy")))
.ok_or(CreddyError::DirNotFound)?;
AppConfig::load_from(data_dir)
let runtime_dir = env::var_os("CREDDY_RUNTIME_DIR")
.map(PathBuf::from)
.or_else(|| dirs::runtime_dir())
.ok_or(CreddyError::DirNotFound)?;
AppConfig::load_from(data_dir, runtime_dir)
}
pub fn load_from(data_dir: PathBuf) -> Result<AppConfig, CreddyError> {
pub fn load_from(data_dir: PathBuf, runtime_dir: PathBuf) -> Result<AppConfig, CreddyError> {
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
let private_config = PrivateConfig::default();
Ok(AppConfig::from_parts(data_dir, public_config, private_config))
}
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
creddy_data_dir
.map(PathBuf::from)
.or_else(|| platform_data_dir.map(|d| d.join("creddy")))
.ok_or(CreddyError::DataDirNotFound)
Ok(AppConfig::from_parts(data_dir, runtime_dir, public_config, private_config))
}
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
fn from_parts(data_dir: PathBuf, public: PublicConfig, private: PrivateConfig) -> AppConfig {
fn from_parts(
data_dir: PathBuf,
runtime_dir: PathBuf,
public: PublicConfig,
private: PrivateConfig
) -> AppConfig {
AppConfig {
data_dir,
runtime_dir,
db_salt: public.db_salt,
rehide_ms: private.rehide_ms,
}
@@ -109,6 +114,10 @@ impl AppConfig {
self.data_dir.join("creddy.duckdb")
}
pub fn creddy_server_addr(&self) -> PathBuf {
self.runtime_dir.join("creddy-server.sock")
}
pub fn public_config(&self) -> PublicConfig {
PublicConfig {
db_salt: self.db_salt,
@@ -128,6 +137,7 @@ impl Default for AppConfig {
// remaining defaults when constructing otherwise, and data_dir is
// always specified otherwise
AppConfig::from_parts(
PathBuf::from(""),
PathBuf::from(""),
PublicConfig::default(),
PrivateConfig::default(),
@@ -174,7 +184,8 @@ mod tests {
#[test]
fn test_config_load_not_present() -> TestResult {
let data_dir = tempfile::tempdir()?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
let data_dir_path = data_dir.path().to_path_buf();
let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?;
assert!(config.data_dir == data_dir.path());
assert!(config.db_salt.len() == 32);
Ok(())
@@ -183,38 +194,18 @@ mod tests {
#[test]
fn test_config_load_present() -> TestResult {
let data_dir = tempfile::tempdir()?;
let data_dir_path = data_dir.path().to_path_buf();
let p = data_dir.path().join("public_config.json");
let public = PublicConfig::default(); // uses a random db salt
let f = File::create(&p)?;
serde_json::to_writer(f, &public)?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?;
assert!(config.data_dir == data_dir.path());
assert!(config.db_salt == public.db_salt);
Ok(())
}
#[test]
fn test_resolve_data_dir_override() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
Some(OsString::from("/tmp/creddy")),
None,
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test]
fn test_resolve_data_dir_default() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
None,
Some(PathBuf::from("/tmp")),
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test]
fn test_config_paths() {
let mut config = AppConfig::default();
@@ -224,6 +215,14 @@ mod tests {
assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json"));
}
#[test]
fn test_server_addr() {
let mut config = AppConfig::default();
config.runtime_dir = PathBuf::from("/tmp/creddy");
assert_eq!(config.creddy_server_addr(), PathBuf::from("/tmp/creddy/creddy-server.sock"));
}
#[test]
fn test_public_config_from_app_config() {
let mut config = AppConfig::default();
+1 -1
View File
@@ -44,7 +44,7 @@ mod tests {
}
#[test]
fn test_load_priate_config() -> TestResult {
fn test_load_private_config() -> TestResult {
let (db, _data_dir) = test_db()?;
let private_config = PrivateConfig::default();
db.save_private_config(&private_config)?;
+4 -1
View File
@@ -5,7 +5,7 @@ use thiserror::Error;
#[derive(Error, Debug)]
pub enum CreddyError {
#[error("Couldn't determine location for app state")]
DataDirNotFound,
DirNotFound,
#[error("Invalid path: {0:?}")]
InvalidPath(OsString),
@@ -30,4 +30,7 @@ pub enum CreddyError {
#[error("Invalid JSON: {0}")]
InvalidJSON(#[from] serde_json::Error),
#[error("Failed to bind socket: {0}")]
SocketBind(String),
}
+1
View File
@@ -15,6 +15,7 @@ mod tests;
use config::AppConfig;
use session::AppSession;
fn main() {
// todo: replace this with proper error handling
let app_config = AppConfig::load().expect("failed to load config");
+69
View File
@@ -0,0 +1,69 @@
use crate::error::CreddyError;
use gpui_kit::AsyncApp;
use http_body_util::Full;
use hyper::{Request, Response, StatusCode};
use hyper::body::{Incoming, Bytes};
use hyper::service::service_fn;
use hyper::server::conn::http1;
use smol::Timer;
use smol::net::unix::{UnixListener, UnixStream};
use smol_hyper::rt::FuturesIo;
use rustix::net::sockopt::socket_peercred;
use rustix::process::Pid;
use std::convert::Infallible;
use std::fs;
use std::io;
use std::path::Path;
use std::time::Duration;
pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> {
if path.exists() {
fs::remove_file(path)?;
}
let listener = UnixListener::bind(path)
.map_err(|_| CreddyError::SocketBind(path.to_string_lossy().into()))?;
app.spawn(async move |app| {
loop {
let (stream, pid) = match accept(&listener).await {
Ok((stream, pid)) => (stream, pid),
Err(e) => {
eprintln!("Error accepting connection: {e}");
Timer::after(Duration::from_millis(100)).await;
continue;
}
};
app.spawn(async move |app| {
let adapter = FuturesIo::new(stream);
let service = service_fn(|req| handle(req, pid, app.clone()));
let conn = http1::Builder::new().serve_connection(adapter, service);
if let Err(e) = conn.await {
eprintln!("Error serving connection: {e}")
}
}).detach();
}
}).detach();
Ok(())
}
async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> {
let (stream, _) = listener.accept().await?;
// pid() never returns None on Linux
let pid = socket_peercred(&stream)?.pid;
Ok((stream, pid))
}
async fn handle(req: Request<Incoming>, pid: Pid, app: AsyncApp) -> Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("hello world"))))
}
fn text(status: StatusCode, body: &'static str) -> Response<Full<Bytes>> {
let mut response = Response::new(Full::new(Bytes::from(body)));
*response.status_mut() = status;
response
}
+3
View File
@@ -0,0 +1,3 @@
mod creddy_server;
pub use creddy_server::start_creddy_server;
+9 -2
View File
@@ -22,7 +22,8 @@ pub struct TestEnv {
impl TestEnv {
pub fn new() -> Result<TestEnv, CreddyError> {
let dir = tempfile::tempdir()?;
let config = AppConfig::load_from(dir.path().to_path_buf())?;
let path = dir.path().to_path_buf();
let config = AppConfig::load_from(path.clone(), path)?;
Ok(TestEnv { _dir: dir, config })
}
@@ -33,7 +34,13 @@ impl TestEnv {
/// Start the app against the test environment, as `main` would.
fn open_app(env: &TestEnv, cx: &mut TestAppContext) -> AnyWindowHandle {
let window = cx.update(|cx| launch(cx, env.config.clone(), AppSession::load(&env.config)));
let window = cx.update(|cx| {
launch(
cx,
env.config.clone(),
AppSession::load(&env.config),
)
});
// first frame, so that elements exist to be found
cx.update_window(window.into(), |_, window, cx| window.render_frame(cx)).unwrap();
window.into()