feat(config): implement configuration system with TOML parser (#2)

- Add LogLevel enum with case-insensitive parsing
- Add OperatingSystem enum with platform detection
- Create config records: Config, ServiceConfig, JobsConfig, CleanupConfig, StorageConfig
- Add ConfigDefaults for platform-specific paths (Unix/Windows)
- Implement TomlParser supporting sections, strings, integers, floats, booleans, arrays
- Create ConfigLoader with:
  - File loading from search paths (system/user config)
  - Environment variable overrides (BARN_SECTION_KEY pattern)
  - Validation of all config values
  - Defaults for missing values
- Add comprehensive tests (93 new tests, 119 total)

Closes #2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 12:59:15 +00:00
1 parent 05937b1f7e
commit 79f89be47c
16 files changed
+2120

No files matched your search

@@ -0,0 +1,64 @@
package com.samsonmedia.barn.config;
/**
* Configuration for automatic job cleanup.
*
* @param enabled whether automatic cleanup is enabled
* @param maxAgeHours remove jobs older than this
* @param cleanupIntervalMinutes how often the cleanup task runs
* @param keepFailedJobs preserve failed jobs for debugging
* @param keepFailedJobsHours how long to keep failed jobs
*/
public record CleanupConfig(
boolean enabled,
int maxAgeHours,
int cleanupIntervalMinutes,
boolean keepFailedJobs,
int keepFailedJobsHours
) {
/** Default enabled state. */
public static final boolean DEFAULT_ENABLED = true;
/** Default max age in hours (3 days). */
public static final int DEFAULT_MAX_AGE_HOURS = 72;
/** Default cleanup interval in minutes. */
public static final int DEFAULT_CLEANUP_INTERVAL_MINUTES = 60;
/** Default keep failed jobs setting. */
public static final boolean DEFAULT_KEEP_FAILED_JOBS = true;
/** Default keep failed jobs hours (1 week). */
public static final int DEFAULT_KEEP_FAILED_JOBS_HOURS = 168;
/**
* Creates a CleanupConfig with validation.
*/
public CleanupConfig {
if (maxAgeHours < 1) {
throw new IllegalArgumentException("maxAgeHours must be at least 1");
}
if (cleanupIntervalMinutes < 1) {
throw new IllegalArgumentException("cleanupIntervalMinutes must be at least 1");
}
if (keepFailedJobsHours < 1) {
throw new IllegalArgumentException("keepFailedJobsHours must be at least 1");
}
}
/**
* Creates a CleanupConfig with default values.
*
* @return a CleanupConfig with all defaults
*/
public static CleanupConfig withDefaults() {
return new CleanupConfig(
DEFAULT_ENABLED,
DEFAULT_MAX_AGE_HOURS,
DEFAULT_CLEANUP_INTERVAL_MINUTES,
DEFAULT_KEEP_FAILED_JOBS,
DEFAULT_KEEP_FAILED_JOBS_HOURS
);
}
}
@@ -0,0 +1,43 @@
package com.samsonmedia.barn.config;
import java.util.Objects;
/**
* Top-level configuration for the Barn application.
*
* @param service service daemon configuration
* @param jobs job execution configuration
* @param cleanup automatic cleanup configuration
* @param storage storage and filesystem configuration
*/
public record Config(
ServiceConfig service,
JobsConfig jobs,
CleanupConfig cleanup,
StorageConfig storage
) {
/**
* Creates a Config with validation.
*/
public Config {
Objects.requireNonNull(service, "service must not be null");
Objects.requireNonNull(jobs, "jobs must not be null");
Objects.requireNonNull(cleanup, "cleanup must not be null");
Objects.requireNonNull(storage, "storage must not be null");
}
/**
* Creates a Config with all default values.
*
* @return a Config with all defaults
*/
public static Config withDefaults() {
return new Config(
ServiceConfig.withDefaults(),
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()
);
}
}
@@ -0,0 +1,92 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Provides platform-specific default values for configuration.
*/
public final class ConfigDefaults {
private ConfigDefaults() {
// Utility class - prevent instantiation
}
/**
* Gets the default base directory for Barn data.
*
* @return the default base directory
*/
public static Path getDefaultBaseDir() {
return switch (OperatingSystem.current()) {
case WINDOWS -> Path.of(System.getenv("TEMP"), "barn");
case LINUX, MACOS -> Path.of("/tmp/barn");
};
}
/**
* Gets the default IPC socket path.
*
* @return the default IPC socket path
*/
public static Path getDefaultIpcSocket() {
return switch (OperatingSystem.current()) {
case WINDOWS -> Path.of("\\\\.\\pipe\\barn");
case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock");
};
}
/**
* Gets the system-wide configuration file path.
*
* @return the system config path
*/
public static Path getSystemConfigPath() {
return switch (OperatingSystem.current()) {
case WINDOWS -> {
String programData = System.getenv("PROGRAMDATA");
if (programData == null || programData.isBlank()) {
programData = "C:\\ProgramData";
}
yield Path.of(programData, "barn", "barn.conf");
}
case LINUX, MACOS -> Path.of("/etc/barn/barn.conf");
};
}
/**
* Gets the user-specific configuration file path.
*
* @return the user config path
*/
public static Path getUserConfigPath() {
String userHome = System.getProperty("user.home", "");
return switch (OperatingSystem.current()) {
case WINDOWS -> {
String appData = System.getenv("APPDATA");
if (appData == null || appData.isBlank()) {
appData = Path.of(userHome, "AppData", "Roaming").toString();
}
yield Path.of(appData, "barn", "barn.conf");
}
case MACOS -> Path.of(userHome, "Library", "Application Support", "barn", "barn.conf");
case LINUX -> Path.of(userHome, ".config", "barn", "barn.conf");
};
}
/**
* Gets the list of configuration file paths in priority order.
*
* <p>Paths are returned in order of increasing priority - later paths
* override earlier ones.
*
* @return list of config paths to check
*/
public static List<Path> getConfigSearchPaths() {
List<Path> paths = new ArrayList<>();
paths.add(getSystemConfigPath());
paths.add(getUserConfigPath());
return paths;
}
}
@@ -0,0 +1,319 @@
package com.samsonmedia.barn.config;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads and validates Barn configuration from files and environment variables.
*
* <p>Configuration is loaded in the following priority order (later overrides earlier):
* <ol>
* <li>Default values</li>
* <li>System config file (e.g., /etc/barn/barn.conf)</li>
* <li>User config file (e.g., ~/.config/barn/barn.conf)</li>
* <li>Explicit config file (via --config flag)</li>
* <li>Environment variables (BARN_SECTION_KEY format)</li>
* </ol>
*/
public final class ConfigLoader {
private static final Logger LOG = LoggerFactory.getLogger(ConfigLoader.class);
private static final String ENV_PREFIX = "BARN_";
private final Map<String, String> environment;
/**
* Creates a ConfigLoader using the system environment.
*/
public ConfigLoader() {
this(System.getenv());
}
/**
* Creates a ConfigLoader with a custom environment (for testing).
*
* @param environment the environment variables to use
*/
public ConfigLoader(Map<String, String> environment) {
this.environment = Objects.requireNonNull(environment, "environment must not be null");
}
/**
* Loads configuration using default search paths.
*
* @return the loaded configuration
* @throws ConfigException if configuration is invalid
*/
public Config load() {
return load(Optional.empty());
}
/**
* Loads configuration, optionally with an explicit config file.
*
* @param explicitPath optional explicit config file path
* @return the loaded configuration
* @throws ConfigException if configuration is invalid
*/
public Config load(Optional<Path> explicitPath) {
Objects.requireNonNull(explicitPath, "explicitPath must not be null");
Map<String, Map<String, Object>> merged = new HashMap<>();
// Load from search paths
for (Path path : ConfigDefaults.getConfigSearchPaths()) {
loadIfExists(path).ifPresent(data -> mergeInto(merged, data));
}
// Load from explicit path if provided
explicitPath.flatMap(this::loadIfExists).ifPresent(data -> mergeInto(merged, data));
// Apply environment overrides
applyEnvironmentOverrides(merged);
return buildConfig(merged);
}
/**
* Loads configuration from a specific file.
*
* @param path the path to the config file
* @return the loaded configuration
* @throws ConfigException if the file cannot be read or is invalid
*/
public Config loadFromFile(Path path) {
Objects.requireNonNull(path, "path must not be null");
Map<String, Map<String, Object>> data = loadFile(path);
applyEnvironmentOverrides(data);
return buildConfig(data);
}
private Optional<Map<String, Map<String, Object>>> loadIfExists(Path path) {
if (!Files.exists(path)) {
LOG.debug("Config file not found: {}", path);
return Optional.empty();
}
try {
return Optional.of(loadFile(path));
} catch (ConfigException e) {
LOG.warn("Failed to load config file {}: {}", path, e.getMessage());
return Optional.empty();
}
}
private Map<String, Map<String, Object>> loadFile(Path path) {
LOG.debug("Loading config from: {}", path);
try {
String content = Files.readString(path);
return TomlParser.parse(content);
} catch (IOException e) {
throw new ConfigException("Failed to read config file: " + path, e);
} catch (TomlParser.TomlParseException e) {
throw new ConfigException("Failed to parse config file: " + path + " - " + e.getMessage(), e);
}
}
private void mergeInto(Map<String, Map<String, Object>> target,
Map<String, Map<String, Object>> source) {
for (Map.Entry<String, Map<String, Object>> entry : source.entrySet()) {
target.computeIfAbsent(entry.getKey(), k -> new HashMap<>())
.putAll(entry.getValue());
}
}
private void applyEnvironmentOverrides(Map<String, Map<String, Object>> data) {
for (Map.Entry<String, String> entry : environment.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!key.startsWith(ENV_PREFIX) || key.equals(ENV_PREFIX)) {
continue;
}
String remainder = key.substring(ENV_PREFIX.length());
int underscoreIndex = remainder.indexOf('_');
if (underscoreIndex <= 0) {
continue;
}
String section = remainder.substring(0, underscoreIndex).toLowerCase();
String configKey = remainder.substring(underscoreIndex + 1).toLowerCase();
LOG.debug("Applying environment override: {}={}", key, value);
data.computeIfAbsent(section, k -> new HashMap<>())
.put(configKey, parseEnvValue(value));
}
}
private Object parseEnvValue(String value) {
if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
return Boolean.parseBoolean(value);
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
// Not an integer
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
// Not a double
}
return value;
}
private Config buildConfig(Map<String, Map<String, Object>> data) {
return new Config(
buildServiceConfig(data.getOrDefault("service", Map.of())),
buildJobsConfig(data.getOrDefault("jobs", Map.of())),
buildCleanupConfig(data.getOrDefault("cleanup", Map.of())),
buildStorageConfig(data.getOrDefault("storage", Map.of()))
);
}
private ServiceConfig buildServiceConfig(Map<String, Object> data) {
return new ServiceConfig(
getOrDefault(data, "log_level", ServiceConfig.DEFAULT_LOG_LEVEL,
v -> LogLevel.fromString(v.toString())),
getOrDefault(data, "max_concurrent_jobs", ServiceConfig.DEFAULT_MAX_CONCURRENT_JOBS,
this::toInt),
getOrDefault(data, "heartbeat_interval_seconds", ServiceConfig.DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
this::toInt),
getOrDefault(data, "ipc_socket", ConfigDefaults.getDefaultIpcSocket(),
v -> Path.of(v.toString())),
getOrDefault(data, "stale_heartbeat_threshold_seconds",
ServiceConfig.DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS, this::toInt)
);
}
private JobsConfig buildJobsConfig(Map<String, Object> data) {
return new JobsConfig(
getOrDefault(data, "default_timeout_seconds", JobsConfig.DEFAULT_TIMEOUT_SECONDS,
this::toInt),
getOrDefault(data, "max_retries", JobsConfig.DEFAULT_MAX_RETRIES,
this::toInt),
getOrDefault(data, "retry_delay_seconds", JobsConfig.DEFAULT_RETRY_DELAY_SECONDS,
this::toInt),
getOrDefault(data, "retry_backoff_multiplier", JobsConfig.DEFAULT_RETRY_BACKOFF_MULTIPLIER,
this::toDouble),
getOrDefault(data, "retry_on_exit_codes", List.of(),
this::toIntList)
);
}
private CleanupConfig buildCleanupConfig(Map<String, Object> data) {
return new CleanupConfig(
getOrDefault(data, "enabled", CleanupConfig.DEFAULT_ENABLED,
this::toBoolean),
getOrDefault(data, "max_age_hours", CleanupConfig.DEFAULT_MAX_AGE_HOURS,
this::toInt),
getOrDefault(data, "cleanup_interval_minutes", CleanupConfig.DEFAULT_CLEANUP_INTERVAL_MINUTES,
this::toInt),
getOrDefault(data, "keep_failed_jobs", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS,
this::toBoolean),
getOrDefault(data, "keep_failed_jobs_hours", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS_HOURS,
this::toInt)
);
}
private StorageConfig buildStorageConfig(Map<String, Object> data) {
return new StorageConfig(
getOrDefault(data, "base_dir", ConfigDefaults.getDefaultBaseDir(),
v -> Path.of(v.toString())),
getOrDefault(data, "max_disk_usage_gb", StorageConfig.DEFAULT_MAX_DISK_USAGE_GB,
this::toInt),
getOrDefault(data, "preserve_work_dir", StorageConfig.DEFAULT_PRESERVE_WORK_DIR,
this::toBoolean)
);
}
@SuppressWarnings("unchecked")
private <T> T getOrDefault(Map<String, Object> data, String key, T defaultValue,
Function<Object, T> converter) {
Object value = data.get(key);
if (value == null) {
return defaultValue;
}
try {
if (defaultValue != null && defaultValue.getClass().isInstance(value)) {
return (T) value;
}
return converter.apply(value);
} catch (Exception e) {
throw new ConfigException("Invalid value for '" + key + "': " + value, e);
}
}
private int toInt(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
return Integer.parseInt(value.toString());
}
private double toDouble(Object value) {
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
return Double.parseDouble(value.toString());
}
private boolean toBoolean(Object value) {
if (value instanceof Boolean) {
return (Boolean) value;
}
return Boolean.parseBoolean(value.toString());
}
@SuppressWarnings("unchecked")
private List<Integer> toIntList(Object value) {
if (value instanceof List) {
List<?> list = (List<?>) value;
List<Integer> result = new ArrayList<>(list.size());
for (Object item : list) {
result.add(toInt(item));
}
return result;
}
throw new ConfigException("Expected list but got: " + value.getClass().getSimpleName());
}
/**
* Exception thrown when configuration loading or validation fails.
*/
public static class ConfigException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new ConfigException.
*
* @param message the error message
*/
public ConfigException(String message) {
super(message);
}
/**
* Creates a new ConfigException with a cause.
*
* @param message the error message
* @param cause the underlying cause
*/
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,69 @@
package com.samsonmedia.barn.config;
import java.util.List;
import java.util.Objects;
/**
* Configuration for job execution behavior.
*
* @param defaultTimeoutSeconds maximum time a job can run before being killed
* @param maxRetries number of retry attempts for failed jobs
* @param retryDelaySeconds initial delay before first retry
* @param retryBackoffMultiplier multiplier applied to delay after each retry
* @param retryOnExitCodes only retry on these exit codes (empty = retry all failures)
*/
public record JobsConfig(
int defaultTimeoutSeconds,
int maxRetries,
int retryDelaySeconds,
double retryBackoffMultiplier,
List<Integer> retryOnExitCodes
) {
/** Default job timeout in seconds (1 hour). */
public static final int DEFAULT_TIMEOUT_SECONDS = 3600;
/** Default maximum number of retries. */
public static final int DEFAULT_MAX_RETRIES = 3;
/** Default retry delay in seconds. */
public static final int DEFAULT_RETRY_DELAY_SECONDS = 30;
/** Default retry backoff multiplier. */
public static final double DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2.0;
/**
* Creates a JobsConfig with validation.
*/
public JobsConfig {
Objects.requireNonNull(retryOnExitCodes, "retryOnExitCodes must not be null");
if (defaultTimeoutSeconds < 1) {
throw new IllegalArgumentException("defaultTimeoutSeconds must be at least 1");
}
if (maxRetries < 0) {
throw new IllegalArgumentException("maxRetries must be non-negative");
}
if (retryDelaySeconds < 0) {
throw new IllegalArgumentException("retryDelaySeconds must be non-negative");
}
if (retryBackoffMultiplier < 1.0) {
throw new IllegalArgumentException("retryBackoffMultiplier must be at least 1.0");
}
retryOnExitCodes = List.copyOf(retryOnExitCodes);
}
/**
* Creates a JobsConfig with default values.
*
* @return a JobsConfig with all defaults
*/
public static JobsConfig withDefaults() {
return new JobsConfig(
DEFAULT_TIMEOUT_SECONDS,
DEFAULT_MAX_RETRIES,
DEFAULT_RETRY_DELAY_SECONDS,
DEFAULT_RETRY_BACKOFF_MULTIPLIER,
List.of()
);
}
}
@@ -0,0 +1,30 @@
package com.samsonmedia.barn.config;
/**
* Log level for the Barn service.
*/
public enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR;
/**
* Parses a log level from a string (case-insensitive).
*
* @param value the string value to parse
* @return the parsed LogLevel
* @throws IllegalArgumentException if the value is not a valid log level
*/
public static LogLevel fromString(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Log level cannot be null or blank");
}
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid log level: '" + value + "'. Valid values are: debug, info, warn, error");
}
}
}
@@ -0,0 +1,44 @@
package com.samsonmedia.barn.config;
/**
* Represents the operating system Barn is running on.
*/
public enum OperatingSystem {
LINUX,
MACOS,
WINDOWS;
private static OperatingSystem detected;
/**
* Detects the current operating system.
*
* @return the detected operating system
*/
public static OperatingSystem current() {
if (detected == null) {
detected = detect();
}
return detected;
}
private static OperatingSystem detect() {
String osName = System.getProperty("os.name", "").toLowerCase();
if (osName.contains("win")) {
return WINDOWS;
} else if (osName.contains("mac") || osName.contains("darwin")) {
return MACOS;
} else {
return LINUX;
}
}
/**
* Checks if the current OS is Unix-like (Linux or macOS).
*
* @return true if Unix-like, false otherwise
*/
public boolean isUnixLike() {
return this == LINUX || this == MACOS;
}
}
@@ -0,0 +1,66 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.Objects;
/**
* Configuration for the Barn service daemon.
*
* @param logLevel the logging verbosity level
* @param maxConcurrentJobs maximum number of jobs running simultaneously
* @param heartbeatIntervalSeconds how often running jobs update their heartbeat
* @param ipcSocket path to the IPC socket for CLI communication
* @param staleHeartbeatThresholdSeconds heartbeat age before a job is considered orphaned
*/
public record ServiceConfig(
LogLevel logLevel,
int maxConcurrentJobs,
int heartbeatIntervalSeconds,
Path ipcSocket,
int staleHeartbeatThresholdSeconds
) {
/** Default log level. */
public static final LogLevel DEFAULT_LOG_LEVEL = LogLevel.INFO;
/** Default maximum concurrent jobs. */
public static final int DEFAULT_MAX_CONCURRENT_JOBS = 4;
/** Default heartbeat interval in seconds. */
public static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 5;
/** Default stale heartbeat threshold in seconds. */
public static final int DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS = 30;
/**
* Creates a ServiceConfig with validation.
*/
public ServiceConfig {
Objects.requireNonNull(logLevel, "logLevel must not be null");
Objects.requireNonNull(ipcSocket, "ipcSocket must not be null");
if (maxConcurrentJobs < 1) {
throw new IllegalArgumentException("maxConcurrentJobs must be at least 1");
}
if (heartbeatIntervalSeconds < 1) {
throw new IllegalArgumentException("heartbeatIntervalSeconds must be at least 1");
}
if (staleHeartbeatThresholdSeconds < 1) {
throw new IllegalArgumentException("staleHeartbeatThresholdSeconds must be at least 1");
}
}
/**
* Creates a ServiceConfig with default values.
*
* @return a ServiceConfig with all defaults
*/
public static ServiceConfig withDefaults() {
return new ServiceConfig(
DEFAULT_LOG_LEVEL,
DEFAULT_MAX_CONCURRENT_JOBS,
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
ConfigDefaults.getDefaultIpcSocket(),
DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS
);
}
}
@@ -0,0 +1,47 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.Objects;
/**
* Configuration for storage and filesystem settings.
*
* @param baseDir root directory for all Barn data
* @param maxDiskUsageGb maximum disk space Barn can use
* @param preserveWorkDir keep work/input and work/output after job completion
*/
public record StorageConfig(
Path baseDir,
int maxDiskUsageGb,
boolean preserveWorkDir
) {
/** Default max disk usage in GB. */
public static final int DEFAULT_MAX_DISK_USAGE_GB = 50;
/** Default preserve work dir setting. */
public static final boolean DEFAULT_PRESERVE_WORK_DIR = false;
/**
* Creates a StorageConfig with validation.
*/
public StorageConfig {
Objects.requireNonNull(baseDir, "baseDir must not be null");
if (maxDiskUsageGb < 1) {
throw new IllegalArgumentException("maxDiskUsageGb must be at least 1");
}
}
/**
* Creates a StorageConfig with default values.
*
* @return a StorageConfig with all defaults
*/
public static StorageConfig withDefaults() {
return new StorageConfig(
ConfigDefaults.getDefaultBaseDir(),
DEFAULT_MAX_DISK_USAGE_GB,
DEFAULT_PRESERVE_WORK_DIR
);
}
}
@@ -0,0 +1,239 @@
package com.samsonmedia.barn.config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Simple TOML parser supporting the subset of TOML used by Barn configuration.
*
* <p>Supports:
* <ul>
* <li>Sections: [section_name]</li>
* <li>String values: key = "value"</li>
* <li>Integer values: key = 123</li>
* <li>Float values: key = 1.5</li>
* <li>Boolean values: key = true/false</li>
* <li>Array values: key = [1, 2, 3]</li>
* <li>Comments: # comment</li>
* </ul>
*/
public final class TomlParser {
private static final Pattern SECTION_PATTERN = Pattern.compile("^\\s*\\[([a-zA-Z_][a-zA-Z0-9_]*)\\]\\s*$");
private static final Pattern KEY_VALUE_PATTERN = Pattern.compile(
"^\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*(.+)$");
private static final Pattern STRING_PATTERN = Pattern.compile("^\"(.*)\"$");
private static final Pattern INTEGER_PATTERN = Pattern.compile("^-?\\d+$");
private static final Pattern FLOAT_PATTERN = Pattern.compile("^-?\\d+\\.\\d+$");
private static final Pattern BOOLEAN_PATTERN = Pattern.compile("^(true|false)$", Pattern.CASE_INSENSITIVE);
private static final Pattern ARRAY_PATTERN = Pattern.compile("^\\[(.*)\\]$");
private TomlParser() {
// Utility class - prevent instantiation
}
/**
* Parses TOML content from a string.
*
* @param content the TOML content
* @return a map of section names to key-value maps
* @throws TomlParseException if the content cannot be parsed
*/
public static Map<String, Map<String, Object>> parse(String content) {
Objects.requireNonNull(content, "content must not be null");
try {
return parse(new StringReader(content));
} catch (IOException e) {
throw new TomlParseException("Failed to parse TOML content", e);
}
}
/**
* Parses TOML content from a reader.
*
* @param reader the reader to read from
* @return a map of section names to key-value maps
* @throws IOException if reading fails
* @throws TomlParseException if the content cannot be parsed
*/
public static Map<String, Map<String, Object>> parse(Reader reader) throws IOException {
Objects.requireNonNull(reader, "reader must not be null");
Map<String, Map<String, Object>> result = new HashMap<>();
String currentSection = null;
int lineNumber = 0;
try (BufferedReader buffered = new BufferedReader(reader)) {
String line;
while ((line = buffered.readLine()) != null) {
lineNumber++;
line = stripComment(line).trim();
if (line.isEmpty()) {
continue;
}
Matcher sectionMatcher = SECTION_PATTERN.matcher(line);
if (sectionMatcher.matches()) {
currentSection = sectionMatcher.group(1);
result.putIfAbsent(currentSection, new HashMap<>());
continue;
}
Matcher keyValueMatcher = KEY_VALUE_PATTERN.matcher(line);
if (keyValueMatcher.matches()) {
if (currentSection == null) {
throw new TomlParseException(
"Key-value pair outside of section at line " + lineNumber);
}
String key = keyValueMatcher.group(1);
String valueStr = keyValueMatcher.group(2).trim();
Object value = parseValue(valueStr, lineNumber);
result.get(currentSection).put(key, value);
continue;
}
throw new TomlParseException("Invalid syntax at line " + lineNumber + ": " + line);
}
}
return result;
}
private static String stripComment(String line) {
int commentIndex = -1;
boolean inString = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"' && (i == 0 || line.charAt(i - 1) != '\\')) {
inString = !inString;
} else if (c == '#' && !inString) {
commentIndex = i;
break;
}
}
return commentIndex >= 0 ? line.substring(0, commentIndex) : line;
}
private static Object parseValue(String valueStr, int lineNumber) {
Matcher stringMatcher = STRING_PATTERN.matcher(valueStr);
if (stringMatcher.matches()) {
return unescapeString(stringMatcher.group(1));
}
if (BOOLEAN_PATTERN.matcher(valueStr).matches()) {
return Boolean.parseBoolean(valueStr);
}
if (INTEGER_PATTERN.matcher(valueStr).matches()) {
try {
return Integer.parseInt(valueStr);
} catch (NumberFormatException e) {
try {
return Long.parseLong(valueStr);
} catch (NumberFormatException e2) {
throw new TomlParseException(
"Integer value too large at line " + lineNumber + ": " + valueStr);
}
}
}
if (FLOAT_PATTERN.matcher(valueStr).matches()) {
return Double.parseDouble(valueStr);
}
Matcher arrayMatcher = ARRAY_PATTERN.matcher(valueStr);
if (arrayMatcher.matches()) {
return parseArray(arrayMatcher.group(1), lineNumber);
}
throw new TomlParseException("Cannot parse value at line " + lineNumber + ": " + valueStr);
}
private static List<Object> parseArray(String content, int lineNumber) {
List<Object> result = new ArrayList<>();
if (content.trim().isEmpty()) {
return result;
}
StringBuilder current = new StringBuilder();
int depth = 0;
boolean inString = false;
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
if (c == '"' && (i == 0 || content.charAt(i - 1) != '\\')) {
inString = !inString;
current.append(c);
} else if (c == '[' && !inString) {
depth++;
current.append(c);
} else if (c == ']' && !inString) {
depth--;
current.append(c);
} else if (c == ',' && depth == 0 && !inString) {
String value = current.toString().trim();
if (!value.isEmpty()) {
result.add(parseValue(value, lineNumber));
}
current = new StringBuilder();
} else {
current.append(c);
}
}
String remaining = current.toString().trim();
if (!remaining.isEmpty()) {
result.add(parseValue(remaining, lineNumber));
}
return result;
}
private static String unescapeString(String str) {
return str
.replace("\\\"", "\"")
.replace("\\\\", "\\")
.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\r", "\r");
}
/**
* Exception thrown when TOML parsing fails.
*/
public static class TomlParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new TomlParseException.
*
* @param message the error message
*/
public TomlParseException(String message) {
super(message);
}
/**
* Creates a new TomlParseException with a cause.
*
* @param message the error message
* @param cause the underlying cause
*/
public TomlParseException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,80 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Tests for ConfigDefaults.
*/
class ConfigDefaultsTest {
@Test
void getDefaultBaseDir_shouldReturnNonNullPath() {
Path baseDir = ConfigDefaults.getDefaultBaseDir();
assertThat(baseDir).isNotNull();
assertThat(baseDir.toString()).isNotEmpty();
}
@Test
void getDefaultIpcSocket_shouldReturnNonNullPath() {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket).isNotNull();
assertThat(socket.toString()).isNotEmpty();
}
@Test
void getSystemConfigPath_shouldReturnNonNullPath() {
Path configPath = ConfigDefaults.getSystemConfigPath();
assertThat(configPath).isNotNull();
assertThat(configPath.toString()).contains("barn.conf");
}
@Test
void getUserConfigPath_shouldReturnNonNullPath() {
Path configPath = ConfigDefaults.getUserConfigPath();
assertThat(configPath).isNotNull();
assertThat(configPath.toString()).contains("barn.conf");
}
@Test
void getConfigSearchPaths_shouldReturnNonEmptyList() {
List<Path> paths = ConfigDefaults.getConfigSearchPaths();
assertThat(paths).isNotEmpty();
assertThat(paths).hasSize(2);
}
@Test
void getConfigSearchPaths_shouldIncludeSystemAndUserPaths() {
List<Path> paths = ConfigDefaults.getConfigSearchPaths();
assertThat(paths).contains(ConfigDefaults.getSystemConfigPath());
assertThat(paths).contains(ConfigDefaults.getUserConfigPath());
}
@Test
void getDefaultBaseDir_onUnix_shouldBeInTmp() {
if (OperatingSystem.current().isUnixLike()) {
Path baseDir = ConfigDefaults.getDefaultBaseDir();
assertThat(baseDir.toString()).startsWith("/tmp");
}
}
@Test
void getDefaultIpcSocket_onUnix_shouldBeUnixSocket() {
if (OperatingSystem.current().isUnixLike()) {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket.toString()).contains("barn.sock");
}
}
@Test
void getDefaultIpcSocket_onWindows_shouldBeNamedPipe() {
if (OperatingSystem.current() == OperatingSystem.WINDOWS) {
Path socket = ConfigDefaults.getDefaultIpcSocket();
assertThat(socket.toString()).contains("pipe");
}
}
}
@@ -0,0 +1,321 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for ConfigLoader.
*/
class ConfigLoaderTest {
@TempDir
private Path tempDir;
@Nested
class DefaultLoading {
@Test
void load_withNoConfigFiles_shouldReturnDefaults() {
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load();
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(4);
assertThat(config.jobs().maxRetries()).isEqualTo(3);
assertThat(config.cleanup().enabled()).isTrue();
}
}
@Nested
class FileLoading {
@Test
void loadFromFile_withValidFile_shouldParseValues() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "debug"
max_concurrent_jobs = 8
[jobs]
max_retries = 5
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().logLevel()).isEqualTo(LogLevel.DEBUG);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(8);
assertThat(config.jobs().maxRetries()).isEqualTo(5);
}
@Test
void loadFromFile_withPartialConfig_shouldUseDefaultsForMissing() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "warn"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().logLevel()).isEqualTo(LogLevel.WARN);
assertThat(config.service().maxConcurrentJobs()).isEqualTo(4); // Default
assertThat(config.jobs().maxRetries()).isEqualTo(3); // Default
}
@Test
void loadFromFile_withNonexistentFile_shouldThrowException() {
Path configFile = tempDir.resolve("nonexistent.conf");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("Failed to read");
}
@Test
void loadFromFile_withInvalidToml_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("invalid.conf");
Files.writeString(configFile, """
not valid toml
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("Failed to parse");
}
}
@Nested
class EnvironmentOverrides {
@Test
void load_withEnvOverride_shouldOverrideFileValue() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "info"
""");
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_LOG_LEVEL", "debug");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load(Optional.of(configFile));
assertThat(config.service().logLevel()).isEqualTo(LogLevel.DEBUG);
}
@Test
void load_withEnvOverrideInteger_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_MAX_CONCURRENT_JOBS", "16");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.service().maxConcurrentJobs()).isEqualTo(16);
}
@Test
void load_withEnvOverrideBoolean_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_CLEANUP_ENABLED", "false");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.cleanup().enabled()).isFalse();
}
@Test
void load_withEnvOverrideFloat_shouldParseCorrectly() {
Map<String, String> env = new HashMap<>();
env.put("BARN_JOBS_RETRY_BACKOFF_MULTIPLIER", "3.5");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.jobs().retryBackoffMultiplier()).isEqualTo(3.5);
}
@Test
void load_withMultipleEnvOverrides_shouldApplyAll() {
Map<String, String> env = new HashMap<>();
env.put("BARN_SERVICE_LOG_LEVEL", "error");
env.put("BARN_JOBS_MAX_RETRIES", "10");
env.put("BARN_CLEANUP_MAX_AGE_HOURS", "24");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
assertThat(config.service().logLevel()).isEqualTo(LogLevel.ERROR);
assertThat(config.jobs().maxRetries()).isEqualTo(10);
assertThat(config.cleanup().maxAgeHours()).isEqualTo(24);
}
@Test
void load_withNonBarnEnvVars_shouldIgnore() {
Map<String, String> env = new HashMap<>();
env.put("PATH", "/usr/bin");
env.put("HOME", "/home/user");
env.put("SOME_OTHER_VAR", "value");
ConfigLoader loader = new ConfigLoader(env);
Config config = loader.load();
// Should load defaults without error
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
}
}
@Nested
class PathConfiguration {
@Test
void load_withIpcSocketPath_shouldParsePath() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
ipc_socket = "/custom/path/barn.sock"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.service().ipcSocket()).isEqualTo(Path.of("/custom/path/barn.sock"));
}
@Test
void load_withBaseDir_shouldParsePath() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[storage]
base_dir = "/data/barn"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.storage().baseDir()).isEqualTo(Path.of("/data/barn"));
}
}
@Nested
class ValidationErrors {
@Test
void load_withInvalidLogLevel_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
log_level = "invalid"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(ConfigLoader.ConfigException.class)
.hasMessageContaining("log_level");
}
@Test
void load_withInvalidMaxConcurrentJobs_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[service]
max_concurrent_jobs = 0
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxConcurrentJobs");
}
@Test
void load_withInvalidBackoffMultiplier_shouldThrowException() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_backoff_multiplier = 0.5
""");
ConfigLoader loader = new ConfigLoader(Map.of());
assertThatThrownBy(() -> loader.loadFromFile(configFile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryBackoffMultiplier");
}
}
@Nested
class ExplicitPathLoading {
@Test
void load_withExplicitPath_shouldUseExplicitPath() throws IOException {
Path configFile = tempDir.resolve("custom.conf");
Files.writeString(configFile, """
[service]
log_level = "error"
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load(Optional.of(configFile));
assertThat(config.service().logLevel()).isEqualTo(LogLevel.ERROR);
}
@Test
void load_withEmptyExplicitPath_shouldUseDefaults() {
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.load(Optional.empty());
assertThat(config.service().logLevel()).isEqualTo(LogLevel.INFO);
}
}
@Nested
class RetryOnExitCodes {
@Test
void load_withRetryOnExitCodes_shouldParseList() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_on_exit_codes = [1, 2, 255]
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.jobs().retryOnExitCodes()).containsExactly(1, 2, 255);
}
@Test
void load_withEmptyRetryOnExitCodes_shouldReturnEmptyList() throws IOException {
Path configFile = tempDir.resolve("barn.conf");
Files.writeString(configFile, """
[jobs]
retry_on_exit_codes = []
""");
ConfigLoader loader = new ConfigLoader(Map.of());
Config config = loader.loadFromFile(configFile);
assertThat(config.jobs().retryOnExitCodes()).isEmpty();
}
}
}
@@ -0,0 +1,266 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for configuration record classes.
*/
class ConfigTest {
@Nested
class ServiceConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
ServiceConfig config = new ServiceConfig(
LogLevel.DEBUG, 8, 10, Path.of("/tmp/barn.sock"), 60);
assertThat(config.logLevel()).isEqualTo(LogLevel.DEBUG);
assertThat(config.maxConcurrentJobs()).isEqualTo(8);
assertThat(config.heartbeatIntervalSeconds()).isEqualTo(10);
assertThat(config.ipcSocket()).isEqualTo(Path.of("/tmp/barn.sock"));
assertThat(config.staleHeartbeatThresholdSeconds()).isEqualTo(60);
}
@Test
void constructor_withNullLogLevel_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
null, 4, 5, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("logLevel");
}
@Test
void constructor_withNullIpcSocket_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 4, 5, null, 30))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("ipcSocket");
}
@Test
void constructor_withZeroMaxConcurrentJobs_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 0, 5, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxConcurrentJobs");
}
@Test
void constructor_withZeroHeartbeatInterval_shouldThrowException() {
assertThatThrownBy(() -> new ServiceConfig(
LogLevel.INFO, 4, 0, Path.of("/tmp/barn.sock"), 30))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("heartbeatIntervalSeconds");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
ServiceConfig config = ServiceConfig.withDefaults();
assertThat(config.logLevel()).isEqualTo(LogLevel.INFO);
assertThat(config.maxConcurrentJobs()).isEqualTo(4);
assertThat(config.heartbeatIntervalSeconds()).isEqualTo(5);
assertThat(config.staleHeartbeatThresholdSeconds()).isEqualTo(30);
assertThat(config.ipcSocket()).isNotNull();
}
}
@Nested
class JobsConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
JobsConfig config = new JobsConfig(7200, 5, 60, 3.0, List.of(1, 2, 3));
assertThat(config.defaultTimeoutSeconds()).isEqualTo(7200);
assertThat(config.maxRetries()).isEqualTo(5);
assertThat(config.retryDelaySeconds()).isEqualTo(60);
assertThat(config.retryBackoffMultiplier()).isEqualTo(3.0);
assertThat(config.retryOnExitCodes()).containsExactly(1, 2, 3);
}
@Test
void constructor_withNullRetryOnExitCodes_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, 3, 30, 2.0, null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("retryOnExitCodes");
}
@Test
void constructor_withZeroTimeout_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(0, 3, 30, 2.0, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("defaultTimeoutSeconds");
}
@Test
void constructor_withNegativeMaxRetries_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, -1, 30, 2.0, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxRetries");
}
@Test
void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() {
assertThatThrownBy(() -> new JobsConfig(3600, 3, 30, 0.5, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryBackoffMultiplier");
}
@Test
void constructor_shouldCreateDefensiveCopyOfExitCodes() {
List<Integer> codes = new java.util.ArrayList<>();
codes.add(1);
JobsConfig config = new JobsConfig(3600, 3, 30, 2.0, codes);
codes.add(2);
assertThat(config.retryOnExitCodes()).containsExactly(1);
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
JobsConfig config = JobsConfig.withDefaults();
assertThat(config.defaultTimeoutSeconds()).isEqualTo(3600);
assertThat(config.maxRetries()).isEqualTo(3);
assertThat(config.retryDelaySeconds()).isEqualTo(30);
assertThat(config.retryBackoffMultiplier()).isEqualTo(2.0);
assertThat(config.retryOnExitCodes()).isEmpty();
}
}
@Nested
class CleanupConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
CleanupConfig config = new CleanupConfig(false, 24, 30, false, 48);
assertThat(config.enabled()).isFalse();
assertThat(config.maxAgeHours()).isEqualTo(24);
assertThat(config.cleanupIntervalMinutes()).isEqualTo(30);
assertThat(config.keepFailedJobs()).isFalse();
assertThat(config.keepFailedJobsHours()).isEqualTo(48);
}
@Test
void constructor_withZeroMaxAgeHours_shouldThrowException() {
assertThatThrownBy(() -> new CleanupConfig(true, 0, 60, true, 168))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxAgeHours");
}
@Test
void constructor_withZeroCleanupInterval_shouldThrowException() {
assertThatThrownBy(() -> new CleanupConfig(true, 72, 0, true, 168))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cleanupIntervalMinutes");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
CleanupConfig config = CleanupConfig.withDefaults();
assertThat(config.enabled()).isTrue();
assertThat(config.maxAgeHours()).isEqualTo(72);
assertThat(config.cleanupIntervalMinutes()).isEqualTo(60);
assertThat(config.keepFailedJobs()).isTrue();
assertThat(config.keepFailedJobsHours()).isEqualTo(168);
}
}
@Nested
class StorageConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
StorageConfig config = new StorageConfig(Path.of("/data/barn"), 100, true);
assertThat(config.baseDir()).isEqualTo(Path.of("/data/barn"));
assertThat(config.maxDiskUsageGb()).isEqualTo(100);
assertThat(config.preserveWorkDir()).isTrue();
}
@Test
void constructor_withNullBaseDir_shouldThrowException() {
assertThatThrownBy(() -> new StorageConfig(null, 50, false))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("baseDir");
}
@Test
void constructor_withZeroMaxDiskUsage_shouldThrowException() {
assertThatThrownBy(() -> new StorageConfig(Path.of("/tmp/barn"), 0, false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxDiskUsageGb");
}
@Test
void withDefaults_shouldReturnConfigWithDefaultValues() {
StorageConfig config = StorageConfig.withDefaults();
assertThat(config.baseDir()).isNotNull();
assertThat(config.maxDiskUsageGb()).isEqualTo(50);
assertThat(config.preserveWorkDir()).isFalse();
}
}
@Nested
class TopLevelConfigTests {
@Test
void constructor_withValidValues_shouldCreateInstance() {
Config config = new Config(
ServiceConfig.withDefaults(),
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()
);
assertThat(config.service()).isNotNull();
assertThat(config.jobs()).isNotNull();
assertThat(config.cleanup()).isNotNull();
assertThat(config.storage()).isNotNull();
}
@Test
void constructor_withNullService_shouldThrowException() {
assertThatThrownBy(() -> new Config(
null,
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("service");
}
@Test
void constructor_withNullJobs_shouldThrowException() {
assertThatThrownBy(() -> new Config(
ServiceConfig.withDefaults(),
null,
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("jobs");
}
@Test
void withDefaults_shouldReturnFullyPopulatedConfig() {
Config config = Config.withDefaults();
assertThat(config.service()).isNotNull();
assertThat(config.jobs()).isNotNull();
assertThat(config.cleanup()).isNotNull();
assertThat(config.storage()).isNotNull();
}
}
}
@@ -0,0 +1,62 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
/**
* Tests for LogLevel enum.
*/
class LogLevelTest {
@Test
void fromString_withValidLowercase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("debug")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("info")).isEqualTo(LogLevel.INFO);
assertThat(LogLevel.fromString("warn")).isEqualTo(LogLevel.WARN);
assertThat(LogLevel.fromString("error")).isEqualTo(LogLevel.ERROR);
}
@Test
void fromString_withValidUppercase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("DEBUG")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("INFO")).isEqualTo(LogLevel.INFO);
assertThat(LogLevel.fromString("WARN")).isEqualTo(LogLevel.WARN);
assertThat(LogLevel.fromString("ERROR")).isEqualTo(LogLevel.ERROR);
}
@Test
void fromString_withMixedCase_shouldReturnLogLevel() {
assertThat(LogLevel.fromString("Debug")).isEqualTo(LogLevel.DEBUG);
assertThat(LogLevel.fromString("Info")).isEqualTo(LogLevel.INFO);
}
@Test
void fromString_withWhitespace_shouldTrimAndParse() {
assertThat(LogLevel.fromString(" info ")).isEqualTo(LogLevel.INFO);
}
@Test
void fromString_withNull_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null or blank");
}
@Test
void fromString_withBlank_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString(" "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null or blank");
}
@Test
void fromString_withInvalidValue_shouldThrowException() {
assertThatThrownBy(() -> LogLevel.fromString("invalid"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid log level")
.hasMessageContaining("invalid")
.hasMessageContaining("debug, info, warn, error");
}
}
@@ -0,0 +1,40 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* Tests for OperatingSystem enum.
*/
class OperatingSystemTest {
@Test
void current_shouldReturnValidOperatingSystem() {
OperatingSystem os = OperatingSystem.current();
assertThat(os).isNotNull();
assertThat(os).isIn(OperatingSystem.LINUX, OperatingSystem.MACOS, OperatingSystem.WINDOWS);
}
@Test
void current_shouldReturnConsistentValue() {
OperatingSystem first = OperatingSystem.current();
OperatingSystem second = OperatingSystem.current();
assertThat(first).isSameAs(second);
}
@Test
void isUnixLike_forLinux_shouldReturnTrue() {
assertThat(OperatingSystem.LINUX.isUnixLike()).isTrue();
}
@Test
void isUnixLike_forMacOS_shouldReturnTrue() {
assertThat(OperatingSystem.MACOS.isUnixLike()).isTrue();
}
@Test
void isUnixLike_forWindows_shouldReturnFalse() {
assertThat(OperatingSystem.WINDOWS.isUnixLike()).isFalse();
}
}
@@ -0,0 +1,338 @@
package com.samsonmedia.barn.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for TomlParser.
*/
class TomlParserTest {
@Nested
class BasicParsing {
@Test
void parse_withEmptyContent_shouldReturnEmptyMap() {
Map<String, Map<String, Object>> result = TomlParser.parse("");
assertThat(result).isEmpty();
}
@Test
void parse_withOnlyComments_shouldReturnEmptyMap() {
String content = """
# This is a comment
# Another comment
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).isEmpty();
}
@Test
void parse_withOnlyWhitespace_shouldReturnEmptyMap() {
String content = " \n \n ";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).isEmpty();
}
}
@Nested
class SectionParsing {
@Test
void parse_withSingleSection_shouldCreateSection() {
String content = "[service]";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKey("service");
}
@Test
void parse_withMultipleSections_shouldCreateAllSections() {
String content = """
[service]
[jobs]
[cleanup]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKeys("service", "jobs", "cleanup");
}
}
@Nested
class StringValueParsing {
@Test
void parse_withStringValue_shouldParseCorrectly() {
String content = """
[service]
log_level = "debug"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("log_level")).isEqualTo("debug");
}
@Test
void parse_withStringContainingSpaces_shouldPreserveSpaces() {
String content = """
[service]
name = "my service name"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("name")).isEqualTo("my service name");
}
@Test
void parse_withEscapedQuotes_shouldUnescape() {
String content = """
[service]
value = "say \\"hello\\""
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("value")).isEqualTo("say \"hello\"");
}
@Test
void parse_withEscapedNewline_shouldUnescape() {
String content = """
[service]
value = "line1\\nline2"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("value")).isEqualTo("line1\nline2");
}
}
@Nested
class IntegerValueParsing {
@Test
void parse_withPositiveInteger_shouldParseCorrectly() {
String content = """
[jobs]
max_retries = 5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("max_retries")).isEqualTo(5);
}
@Test
void parse_withNegativeInteger_shouldParseCorrectly() {
String content = """
[jobs]
value = -10
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(-10);
}
@Test
void parse_withZero_shouldParseCorrectly() {
String content = """
[jobs]
value = 0
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(0);
}
}
@Nested
class FloatValueParsing {
@Test
void parse_withPositiveFloat_shouldParseCorrectly() {
String content = """
[jobs]
multiplier = 2.5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("multiplier")).isEqualTo(2.5);
}
@Test
void parse_withNegativeFloat_shouldParseCorrectly() {
String content = """
[jobs]
value = -1.5
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("value")).isEqualTo(-1.5);
}
}
@Nested
class BooleanValueParsing {
@Test
void parse_withTrueValue_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = true
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
}
@Test
void parse_withFalseValue_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = false
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(false);
}
@Test
void parse_withUppercaseBoolean_shouldParseCorrectly() {
String content = """
[cleanup]
enabled = TRUE
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
}
}
@Nested
class ArrayValueParsing {
@Test
void parse_withEmptyArray_shouldReturnEmptyList() {
String content = """
[jobs]
exit_codes = []
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("exit_codes")).isEqualTo(List.of());
}
@Test
void parse_withIntegerArray_shouldParseCorrectly() {
String content = """
[jobs]
exit_codes = [1, 2, 3]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("exit_codes")).isEqualTo(List.of(1, 2, 3));
}
@Test
void parse_withStringArray_shouldParseCorrectly() {
String content = """
[jobs]
tags = ["a", "b", "c"]
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("jobs").get("tags")).isEqualTo(List.of("a", "b", "c"));
}
}
@Nested
class CommentHandling {
@Test
void parse_withInlineComment_shouldIgnoreComment() {
String content = """
[service]
max_jobs = 4 # This is a comment
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("max_jobs")).isEqualTo(4);
}
@Test
void parse_withCommentInString_shouldPreserveHash() {
String content = """
[service]
name = "job#123"
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result.get("service").get("name")).isEqualTo("job#123");
}
}
@Nested
class ComplexScenarios {
@Test
void parse_withFullConfigFile_shouldParseAllSections() {
String content = """
[service]
log_level = "info"
max_concurrent_jobs = 4
heartbeat_interval_seconds = 5
[jobs]
default_timeout_seconds = 3600
max_retries = 3
retry_delay_seconds = 30
retry_backoff_multiplier = 2.0
retry_on_exit_codes = [1, 2]
[cleanup]
enabled = true
max_age_hours = 72
keep_failed_jobs = true
[storage]
base_dir = "/tmp/barn"
max_disk_usage_gb = 50
""";
Map<String, Map<String, Object>> result = TomlParser.parse(content);
assertThat(result).containsKeys("service", "jobs", "cleanup", "storage");
assertThat(result.get("service").get("log_level")).isEqualTo("info");
assertThat(result.get("jobs").get("retry_on_exit_codes")).isEqualTo(List.of(1, 2));
assertThat(result.get("cleanup").get("enabled")).isEqualTo(true);
assertThat(result.get("storage").get("base_dir")).isEqualTo("/tmp/barn");
}
}
@Nested
class ErrorHandling {
@Test
void parse_withNullContent_shouldThrowException() {
assertThatThrownBy(() -> TomlParser.parse((String) null))
.isInstanceOf(NullPointerException.class);
}
@Test
void parse_withKeyValueOutsideSection_shouldThrowException() {
String content = """
name = "value"
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class)
.hasMessageContaining("outside of section");
}
@Test
void parse_withInvalidSyntax_shouldThrowException() {
String content = """
[service]
this is not valid
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class)
.hasMessageContaining("Invalid syntax");
}
@Test
void parse_withUnterminatedString_shouldThrowException() {
String content = """
[service]
value = "unterminated
""";
assertThatThrownBy(() -> TomlParser.parse(content))
.isInstanceOf(TomlParser.TomlParseException.class);
}
}
}