git-next/src/server/mod.rs

240 lines
7.2 KiB
Rust
Raw Normal View History

mod actors;
2024-04-07 13:47:39 +01:00
mod config;
pub mod gitforge;
pub mod types;
2024-04-07 13:47:39 +01:00
2024-04-07 20:16:04 +01:00
use actix::prelude::*;
2024-04-09 10:44:01 +01:00
use kxio::network::Network;
2024-04-07 20:16:04 +01:00
use std::path::PathBuf;
use tracing::{error, info, level_filters::LevelFilter};
2024-04-07 20:16:04 +01:00
use crate::{
2024-04-28 08:05:09 +01:00
fs::FileSystem,
server::{
actors::webhook,
config::{ForgeConfig, ForgeName, GitDir, RepoAlias, ServerStorage, Webhook},
},
2024-04-07 20:16:04 +01:00
};
use self::{actors::repo::RepoActor, config::ServerRepoConfig};
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
#[display("Failed to create data directories")]
FailedToCreateDataDirectory(kxio::fs::Error),
#[display("The forge data path is not a directory: {path:?}")]
ForgeDirIsNotDirectory {
path: PathBuf,
},
Config(crate::server::config::Error),
Io(std::io::Error),
}
type Result<T> = core::result::Result<T, Error>;
2024-04-07 16:09:16 +01:00
pub fn init(fs: FileSystem) {
let file_name = "git-next-server.toml";
2024-04-28 08:05:09 +01:00
let pathbuf = PathBuf::from(file_name);
let Ok(exists) = fs.path_exists(&pathbuf) else {
eprintln!("Could not check if file exist: {}", file_name);
return;
};
if exists {
eprintln!(
"The configuration file already exists at {} - not overwritting it.",
file_name
);
} else {
2024-04-28 08:05:09 +01:00
match fs.file_write(&pathbuf, include_str!("../../server-default.toml")) {
Ok(_) => println!("Created a default configuration file at {}", file_name),
Err(e) => {
eprintln!("Failed to write to the configuration file: {}", e)
}
}
}
}
pub async fn start(fs: FileSystem, net: Network) {
init_logging();
info!("Starting Server...");
let server_config = match config::ServerConfig::load(&fs) {
Ok(server_config) => server_config,
Err(err) => {
error!("Failed to load config file. Error: {}", err);
return;
}
};
// Server Storage
let dir = server_config.storage().path();
if !dir.exists() {
info!(?dir, "server storage doesn't exist - creating it");
if let Err(err) = fs.dir_create(dir) {
error!(?err, ?dir, "Failed to create server storage");
return;
}
}
let Ok(canon) = dir.canonicalize() else {
error!(?dir, "Failed to confirm servier storage");
return;
};
info!(dir = ?canon, "server storage");
// Forge directories in Server Storage
2024-04-23 07:09:30 +01:00
let server_storage = server_config.storage();
if let Err(err) = create_forge_data_directories(&server_config, &fs, &dir) {
error!(?err, "Failure creating forge storage");
return;
}
// Webhook Server
info!("Starting Webhook Server...");
let webhook_router = webhook::WebhookRouter::new().start();
let webhook = server_config.webhook();
// Forge Actors
for (forge_name, forge_config) in server_config.forges() {
create_forge_repos(
forge_config,
forge_name.clone(),
server_storage,
webhook,
&net,
)
.into_iter()
.map(start_actor)
.map(|(alias, addr)| webhook::AddWebhookRecipient(alias, addr.recipient()))
.for_each(|msg| webhook_router.do_send(msg));
}
let webhook_server = webhook::WebhookActor::new(webhook_router.recipient()).start();
info!("Server running - Press Ctrl-C to stop...");
let _ = actix_rt::signal::ctrl_c().await;
info!("Ctrl-C received, shutting down...");
drop(webhook_server);
}
fn create_forge_data_directories(
server_config: &config::ServerConfig,
fs: &FileSystem,
server_dir: &&std::path::Path,
) -> Result<()> {
for (forge_name, _forge_config) in server_config.forges() {
let forge_dir: PathBuf = (&forge_name).into();
let path = server_dir.join(&forge_dir);
if fs.path_exists(&path)? {
if !fs.path_is_dir(&path)? {
return Err(Error::ForgeDirIsNotDirectory { path });
}
} else {
info!(%forge_name, ?path, "creating storage");
fs.dir_create_all(&path)?;
}
}
Ok(())
}
fn create_forge_repos(
2024-04-23 07:13:16 +01:00
forge_config: &ForgeConfig,
forge_name: ForgeName,
2024-04-23 07:09:30 +01:00
server_storage: &ServerStorage,
webhook: &Webhook,
2024-04-09 10:44:01 +01:00
net: &Network,
) -> Vec<(ForgeName, RepoAlias, RepoActor)> {
let span =
tracing::info_span!("create_forge_repos", name = %forge_name, config = %forge_config);
let _guard = span.enter();
info!("Creating Forge");
let mut repos = vec![];
let creator = create_actor(
forge_name,
forge_config.clone(),
server_storage,
webhook,
net,
);
for (repo_alias, server_repo_config) in forge_config.repos() {
let forge_repo = creator((repo_alias, server_repo_config));
info!(
alias = %forge_repo.1,
"Created Repo"
);
repos.push(forge_repo);
}
repos
}
fn create_actor(
forge_name: ForgeName,
2024-04-23 07:13:16 +01:00
forge_config: config::ForgeConfig,
2024-04-23 07:09:30 +01:00
server_storage: &ServerStorage,
webhook: &Webhook,
2024-04-09 10:44:01 +01:00
net: &Network,
) -> impl Fn((RepoAlias, &ServerRepoConfig)) -> (ForgeName, RepoAlias, RepoActor) {
2024-04-23 07:09:30 +01:00
let server_storage = server_storage.clone();
let webhook = webhook.clone();
2024-04-09 10:44:01 +01:00
let net = net.clone();
move |(repo_alias, server_repo_config)| {
let span =
tracing::info_span!("create_actor", alias = %repo_alias, config = %server_repo_config);
let _guard = span.enter();
info!("Creating Repo");
let gitdir = server_repo_config.gitdir().map_or_else(
|| {
GitDir::from(
server_storage
.path()
.join(forge_name.to_string())
.join(repo_alias.to_string()),
)
},
|gitdir| gitdir,
);
// INFO: can't canonicalise gitdir as the path needs to exist to do that and we may not
// have cloned the repo yet
let repo_details = config::RepoDetails::new(
&repo_alias,
server_repo_config,
&forge_name,
&forge_config,
gitdir,
);
info!("Starting Repo Actor");
let actor = actors::repo::RepoActor::new(repo_details, webhook.clone(), net.clone());
(forge_name.clone(), repo_alias, actor)
}
}
fn start_actor(
actor: (ForgeName, RepoAlias, actors::repo::RepoActor),
) -> (RepoAlias, Addr<actors::repo::RepoActor>) {
let (forge_name, repo_alias, actor) = actor;
let span = tracing::info_span!("start_actor", forge = %forge_name, repo = %repo_alias);
let _guard = span.enter();
info!("Starting");
let addr = actor.start();
2024-04-23 07:09:30 +01:00
addr.do_send(actors::repo::CloneRepo);
info!("Started");
(repo_alias, addr)
}
pub fn init_logging() {
use tracing_subscriber::prelude::*;
let subscriber = tracing_subscriber::fmt::layer()
// NOTE: set RUSTLOG in ${root}/.cargo/config
.with_target(false)
.with_file(true)
.with_line_number(true)
.with_filter(LevelFilter::INFO);
tracing_subscriber::registry()
.with(console_subscriber::ConsoleLayer::builder().spawn())
.with(subscriber)
.init();
}