Page MenuHomeDevCentral

store.rs
No OneTemporary

store.rs

// -------------------------------------------------------------
// Alkane :: Runner :: Recipes store
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Project: Nasqueron
// License: BSD-2-Clause
// -------------------------------------------------------------
use std::collections::HashMap;
use std::path::Path;
use log::{error, info};
use crate::config::AlkaneConfig;
use crate::runner::run;
use crate::runner::site::Site;
use crate::runner::RecipeStatus;
use crate::services::validation::is_valid_site_name;
pub struct RecipesStore {
root: String,
}
impl RecipesStore {
pub fn new<S>(root: S) -> Self
where
S: AsRef<str>,
{
Self {
root: root.as_ref().to_string(),
}
}
pub fn from_config(config: &AlkaneConfig) -> Option<Self> {
config.get_root("recipes").map(Self::new)
}
fn get_recipe_path(&self, site_name: &str, action: &str) -> Option<String> {
if !is_valid_site_name(site_name) {
return None;
}
Path::new(&self.root)
.join(site_name)
.join(action)
.to_str()
.map(str::to_string)
}
pub async fn run_recipe(&self, site: &Site, action: &str) -> RecipeStatus {
let Some(command) = self.resolve_recipe_path(&site.name, action) else {
error!(
"Refusing to run a recipe for invalid site name {:?}",
site.name
);
return RecipeStatus::Error;
};
let environment = self.get_environment(&site);
run(command, Vec::new(), environment).await
}
/// Resolve the recipe to run for a site and action.
///
/// If the update recipe can also initialize a fresh site, a site can omit
/// its init recipe. In that case, init resolves to the update recipe.
fn resolve_recipe_path(&self, site_name: &str, action: &str) -> Option<String> {
let path = self.get_recipe_path(site_name, action)?;
let init_is_absent = action == "init"
&& matches!(
std::fs::symlink_metadata(&path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound
);
if init_is_absent {
let fallback = self.get_recipe_path(site_name, "update")?;
if matches!(Path::new(&fallback).try_exists(), Ok(true)) {
info!(
"No init recipe for {}, falling back to the update recipe",
site_name
);
return Some(fallback);
}
}
Some(path)
}
fn get_environment(&self, site: &Site) -> HashMap<String, String> {
let mut map = HashMap::new();
map.insert("ALKANE_RECIPES_PATH".to_string(), self.root.clone());
map.insert("ALKANE_SITE_NAME".to_string(), site.name.clone());
map.insert("ALKANE_SITE_PATH".to_string(), site.path.clone());
if let Some(context) = &site.context {
if !context.is_empty() {
map.insert("ALKANE_SITE_CONTEXT".to_string(), context.clone());
}
}
map
}
}
// -------------------------------------------------------------
// Tests
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#[cfg(test)]
mod tests {
use std::fs;
use std::path::MAIN_SEPARATOR_STR;
use std::path::PathBuf;
use super::*;
#[test]
pub fn test_get_recipe_path() {
let expected = "tests/data/recipes/foo.acme.tld/update".replace("/", MAIN_SEPARATOR_STR);
let test_store_path = "tests/data/recipes".replace("/", MAIN_SEPARATOR_STR);
let store = RecipesStore::new(&test_store_path);
assert_eq!(
Some(expected),
store.get_recipe_path("foo.acme.tld", "update")
);
}
#[test]
pub fn test_get_recipe_path_rejects_traversal() {
let store = RecipesStore::new("tests/data/recipes");
assert_eq!(None, store.get_recipe_path("../foo.acme.tld", "update"));
}
#[test]
pub fn test_get_recipe_path_preserves_idn() {
let expected =
"tests/data/recipes/dæghrefn.nasqueron.org/update".replace("/", MAIN_SEPARATOR_STR);
let store = RecipesStore::new("tests/data/recipes".replace("/", MAIN_SEPARATOR_STR));
assert_eq!(
Some(expected),
store.get_recipe_path("dæghrefn.nasqueron.org", "update")
);
}
#[test]
pub fn test_get_environment() {
let mut expected = HashMap::new();
expected.insert(
"ALKANE_RECIPES_PATH".to_string(),
"tests/data/recipes".replace("/", MAIN_SEPARATOR_STR),
);
expected.insert("ALKANE_SITE_NAME".to_string(), "foo.acme.tld".to_string());
expected.insert(
"ALKANE_SITE_PATH".to_string(),
"tests/data/wwwroot/acme.tld/foo".replace("/", MAIN_SEPARATOR_STR),
);
let test_store_path = "tests/data/recipes".replace("/", MAIN_SEPARATOR_STR);
let store = RecipesStore::new(&test_store_path);
let site = Site {
name: "foo.acme.tld".to_string(),
path: "tests/data/wwwroot/acme.tld/foo".replace("/", MAIN_SEPARATOR_STR),
context: None,
};
assert_eq!(expected, store.get_environment(&site));
}
#[test]
pub fn test_get_environment_with_context() {
let site = Site {
name: "foo.acme.tld".to_string(),
path: "/path/to/site".to_string(),
context: Some("CH3-CH3".to_string()),
};
let environment = RecipesStore::new("/path/to/recipes").get_environment(&site);
assert!(environment.contains_key("ALKANE_SITE_CONTEXT"));
assert_eq!("CH3-CH3", environment["ALKANE_SITE_CONTEXT"])
}
// -------------------------------------------------------------
// Recipe resolution helpers
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
struct TempStore {
root: PathBuf,
store: RecipesStore,
}
impl TempStore {
fn new(name: &str) -> Self {
let root = std::env::temp_dir().join(format!(
"alkane-test-{}-{}",
std::process::id(),
name
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).expect("Can't create temporary recipe store");
let store = RecipesStore::new(root.to_str().expect("Non-UTF8 temp path"));
Self { root, store }
}
}
impl Drop for TempStore {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}
/// Create an empty recipe file for a site and action
fn add_recipe(root: &Path, site_name: &str, action: &str) {
let site_dir = root.join(site_name);
fs::create_dir_all(&site_dir).expect("Can't create site recipe directory");
fs::write(site_dir.join(action), "#!/bin/sh\n").expect("Can't write recipe");
}
// -------------------------------------------------------------
// Recipe resolution tests
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#[test]
pub fn test_resolve_recipe_path_prefers_init() {
let temp = TempStore::new("resolve-prefer-init");
add_recipe(&temp.root, "foo.acme.tld", "init");
add_recipe(&temp.root, "foo.acme.tld", "update");
let expected = temp.root.join("foo.acme.tld").join("init");
assert_eq!(
Some(expected.to_str().unwrap().to_string()),
temp.store.resolve_recipe_path("foo.acme.tld", "init")
);
}
#[test]
pub fn test_resolve_recipe_path_falls_back_to_update() {
let temp = TempStore::new("resolve-fallback");
add_recipe(&temp.root, "foo.acme.tld", "update");
let expected = temp.root.join("foo.acme.tld").join("update");
assert_eq!(
Some(expected.to_str().unwrap().to_string()),
temp.store.resolve_recipe_path("foo.acme.tld", "init")
);
}
#[cfg(unix)]
#[test]
pub fn test_resolve_recipe_path_keeps_dangling_init_symlink() {
let temp = TempStore::new("resolve-dangling-init");
add_recipe(&temp.root, "foo.acme.tld", "update");
let init = temp.root.join("foo.acme.tld").join("init");
std::os::unix::fs::symlink("missing-init-target", &init)
.expect("Can't create dangling init symlink");
assert_eq!(
Some(init.to_str().unwrap().to_string()),
temp.store.resolve_recipe_path("foo.acme.tld", "init")
);
}
#[test]
pub fn test_resolve_recipe_path_update_not_affected_by_fallback() {
let temp = TempStore::new("resolve-update");
add_recipe(&temp.root, "foo.acme.tld", "update");
let expected = temp.root.join("foo.acme.tld").join("update");
assert_eq!(
Some(expected.to_str().unwrap().to_string()),
temp.store.resolve_recipe_path("foo.acme.tld", "update")
);
}
#[test]
pub fn test_resolve_recipe_path_init_without_any_recipe() {
let temp = TempStore::new("resolve-no-recipe");
fs::create_dir_all(temp.root.join("foo.acme.tld")).expect("Can't create site recipe directory");
// No fallback available: the init path is returned as-is,
// and run() will report the missing recipe.
let expected = temp.root.join("foo.acme.tld").join("init");
assert_eq!(
Some(expected.to_str().unwrap().to_string()),
temp.store.resolve_recipe_path("foo.acme.tld", "init")
);
}
#[test]
pub fn test_resolve_recipe_path_rejects_traversal() {
let temp = TempStore::new("resolve-traversal");
assert_eq!(None, temp.store.resolve_recipe_path("../foo.acme.tld", "init"));
assert_eq!(None, temp.store.resolve_recipe_path("../foo.acme.tld", "update"));
}
}

File Metadata

Mime Type
text/plain
Expires
Sun, Nov 15, 01:29 (4 d, 18 h ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4233357
Default Alt Text
store.rs (9 KB)

Event Timeline