feat(state): implement filesystem state management system (#3)

- Add AtomicFiles utility for atomic file operations (write-to-tmp-then-rename)
- Add JobState enum (queued, running, succeeded, failed, canceled)
- Create BarnDirectories for managing directory structure:
  - jobs/, locks/, logs/ top-level directories
  - Per-job: work/input/, work/output/, logs/ subdirectories
  - Lock files for scheduler and individual jobs
- Implement StateFiles for reading/writing job metadata:
  - State, tag, timestamps (created_at, started_at, finished_at, heartbeat)
  - Exit codes (integer and symbolic), error messages
  - PID, retry count, retry history, stage
  - All timestamps in ISO-8601 format
- Add FileLock for cross-process file locking using FileChannel.tryLock()
- Handle OverlappingFileLockException for same-JVM lock attempts
- Add comprehensive tests (92 new tests, 211 total)

Closes #3

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 13:04:01 +00:00
1 parent 79f89be47c
commit 647e602fe9
10 files changed
+1917

No files matched your search

@@ -0,0 +1,120 @@
package com.samsonmedia.barn.state;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
import java.util.Optional;
/**
* Utility class for atomic file operations.
*
* <p>Atomic writes work by writing to a temporary file first, then atomically
* renaming it to the target. This ensures that readers never see partial content.
*/
public final class AtomicFiles {
private static final String TMP_SUFFIX = ".tmp";
private AtomicFiles() {
// Utility class - prevent instantiation
}
/**
* Writes content to a file atomically.
*
* <p>The content is first written to a temporary file, then atomically
* renamed to the target path. This ensures that the target file either
* contains the complete content or doesn't exist.
*
* @param target the target file path
* @param content the content to write
* @throws IOException if writing fails
*/
public static void writeAtomically(Path target, String content) throws IOException {
Objects.requireNonNull(target, "target must not be null");
Objects.requireNonNull(content, "content must not be null");
Path tempFile = target.resolveSibling(target.getFileName() + TMP_SUFFIX);
try {
Files.writeString(tempFile, content,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE);
Files.move(tempFile, target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Clean up temp file on failure
try {
Files.deleteIfExists(tempFile);
} catch (IOException ignored) {
// Best effort cleanup
}
throw e;
}
}
/**
* Reads content from a file safely.
*
* <p>Returns an empty Optional if the file doesn't exist, rather than
* throwing an exception. The content is trimmed of leading/trailing whitespace.
*
* @param path the file to read
* @return the file content, or empty if the file doesn't exist
* @throws IOException if reading fails for reasons other than file not found
*/
public static Optional<String> readSafely(Path path) throws IOException {
Objects.requireNonNull(path, "path must not be null");
try {
String content = Files.readString(path);
return Optional.of(content.trim());
} catch (NoSuchFileException e) {
return Optional.empty();
}
}
/**
* Reads content from a file, returning empty string if not found.
*
* @param path the file to read
* @return the file content, or empty string if the file doesn't exist
* @throws IOException if reading fails for reasons other than file not found
*/
public static String readOrEmpty(Path path) throws IOException {
return readSafely(path).orElse("");
}
/**
* Deletes a file if it exists.
*
* @param path the file to delete
* @return true if the file was deleted, false if it didn't exist
* @throws IOException if deletion fails
*/
public static boolean deleteIfExists(Path path) throws IOException {
Objects.requireNonNull(path, "path must not be null");
return Files.deleteIfExists(path);
}
/**
* Creates parent directories for a file if they don't exist.
*
* @param path the file path
* @throws IOException if directory creation fails
*/
public static void ensureParentDirectories(Path path) throws IOException {
Objects.requireNonNull(path, "path must not be null");
Path parent = path.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
}
}
@@ -0,0 +1,233 @@
package com.samsonmedia.barn.state;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
/**
* Manages the Barn directory structure.
*
* <p>The directory layout is:
* <pre>
* {baseDir}/
* jobs/
* {jobId}/
* work/
* input/
* output/
* logs/
* locks/
* logs/
* </pre>
*/
public final class BarnDirectories {
/** Subdirectory for job data. */
public static final String JOBS_DIR = "jobs";
/** Subdirectory for lock files. */
public static final String LOCKS_DIR = "locks";
/** Subdirectory for daemon logs. */
public static final String LOGS_DIR = "logs";
/** Subdirectory for job working files. */
public static final String WORK_DIR = "work";
/** Subdirectory for input files within work. */
public static final String INPUT_DIR = "input";
/** Subdirectory for output files within work. */
public static final String OUTPUT_DIR = "output";
private final Path baseDir;
/**
* Creates a BarnDirectories instance with the specified base directory.
*
* @param baseDir the base directory for all Barn data
*/
public BarnDirectories(Path baseDir) {
this.baseDir = Objects.requireNonNull(baseDir, "baseDir must not be null");
}
/**
* Returns the base directory.
*
* @return the base directory path
*/
public Path getBaseDir() {
return baseDir;
}
/**
* Returns the jobs directory.
*
* @return the jobs directory path
*/
public Path getJobsDir() {
return baseDir.resolve(JOBS_DIR);
}
/**
* Returns the locks directory.
*
* @return the locks directory path
*/
public Path getLocksDir() {
return baseDir.resolve(LOCKS_DIR);
}
/**
* Returns the daemon logs directory.
*
* @return the logs directory path
*/
public Path getLogsDir() {
return baseDir.resolve(LOGS_DIR);
}
/**
* Returns the directory for a specific job.
*
* @param jobId the job identifier
* @return the job directory path
*/
public Path getJobDir(String jobId) {
Objects.requireNonNull(jobId, "jobId must not be null");
return getJobsDir().resolve(jobId);
}
/**
* Returns the working directory for a specific job.
*
* @param jobId the job identifier
* @return the job work directory path
*/
public Path getJobWorkDir(String jobId) {
return getJobDir(jobId).resolve(WORK_DIR);
}
/**
* Returns the input directory for a specific job.
*
* @param jobId the job identifier
* @return the job input directory path
*/
public Path getJobInputDir(String jobId) {
return getJobWorkDir(jobId).resolve(INPUT_DIR);
}
/**
* Returns the output directory for a specific job.
*
* @param jobId the job identifier
* @return the job output directory path
*/
public Path getJobOutputDir(String jobId) {
return getJobWorkDir(jobId).resolve(OUTPUT_DIR);
}
/**
* Returns the logs directory for a specific job.
*
* @param jobId the job identifier
* @return the job logs directory path
*/
public Path getJobLogsDir(String jobId) {
return getJobDir(jobId).resolve(LOGS_DIR);
}
/**
* Returns the lock file path for a specific job.
*
* @param jobId the job identifier
* @return the job lock file path
*/
public Path getJobLockFile(String jobId) {
Objects.requireNonNull(jobId, "jobId must not be null");
return getLocksDir().resolve("job-" + jobId + ".lock");
}
/**
* Returns the scheduler lock file path.
*
* @return the scheduler lock file path
*/
public Path getSchedulerLockFile() {
return getLocksDir().resolve("scheduler.lock");
}
/**
* Returns the daemon log file path.
*
* @return the daemon log file path
*/
public Path getDaemonLogFile() {
return getLogsDir().resolve("barn.log");
}
/**
* Initializes the top-level directory structure.
*
* <p>Creates the base directory and all subdirectories if they don't exist.
*
* @throws IOException if directory creation fails
*/
public void initialize() throws IOException {
Files.createDirectories(getJobsDir());
Files.createDirectories(getLocksDir());
Files.createDirectories(getLogsDir());
}
/**
* Creates the directory structure for a specific job.
*
* @param jobId the job identifier
* @throws IOException if directory creation fails
*/
public void createJobDirs(String jobId) throws IOException {
Objects.requireNonNull(jobId, "jobId must not be null");
Files.createDirectories(getJobDir(jobId));
Files.createDirectories(getJobInputDir(jobId));
Files.createDirectories(getJobOutputDir(jobId));
Files.createDirectories(getJobLogsDir(jobId));
}
/**
* Checks if a job directory exists.
*
* @param jobId the job identifier
* @return true if the job directory exists
*/
public boolean jobExists(String jobId) {
Objects.requireNonNull(jobId, "jobId must not be null");
return Files.exists(getJobDir(jobId));
}
/**
* Deletes the directory for a specific job.
*
* @param jobId the job identifier
* @throws IOException if deletion fails
*/
public void deleteJobDir(String jobId) throws IOException {
Objects.requireNonNull(jobId, "jobId must not be null");
Path jobDir = getJobDir(jobId);
if (Files.exists(jobDir)) {
deleteRecursively(jobDir);
}
}
private void deleteRecursively(Path path) throws IOException {
if (Files.isDirectory(path)) {
try (var stream = Files.list(path)) {
for (Path child : stream.toList()) {
deleteRecursively(child);
}
}
}
Files.delete(path);
}
}
@@ -0,0 +1,149 @@
package com.samsonmedia.barn.state;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A file-based lock for coordinating access to resources.
*
* <p>Uses {@link FileChannel#tryLock()} for cross-process locking.
* The lock is released when the FileLock is closed.
*/
public final class FileLock implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(FileLock.class);
private final Path lockFile;
private final FileChannel channel;
private final java.nio.channels.FileLock lock;
private FileLock(Path lockFile, FileChannel channel, java.nio.channels.FileLock lock) {
this.lockFile = lockFile;
this.channel = channel;
this.lock = lock;
}
/**
* Attempts to acquire a lock on the specified file.
*
* <p>This is a non-blocking operation. If the lock cannot be acquired
* (because another process holds it), this method returns an empty Optional.
*
* @param lockFile the path to the lock file
* @return the acquired lock, or empty if the lock is already held
* @throws IOException if lock file creation or acquisition fails
*/
public static Optional<FileLock> tryAcquire(Path lockFile) throws IOException {
Objects.requireNonNull(lockFile, "lockFile must not be null");
// Ensure parent directory exists
Path parent = lockFile.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
FileChannel channel = null;
try {
channel = FileChannel.open(lockFile,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
java.nio.channels.FileLock lock;
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// Lock is held by another thread in this JVM
channel.close();
LOG.debug("Could not acquire lock (held by same JVM): {}", lockFile);
return Optional.empty();
}
if (lock == null) {
// Lock is held by another process
channel.close();
LOG.debug("Could not acquire lock: {}", lockFile);
return Optional.empty();
}
LOG.debug("Acquired lock: {}", lockFile);
return Optional.of(new FileLock(lockFile, channel, lock));
} catch (IOException e) {
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
// Best effort cleanup
}
}
throw e;
}
}
/**
* Checks if a lock file is currently locked by another process.
*
* <p>This method tries to acquire the lock temporarily. If it succeeds,
* the lock is immediately released, indicating no one else holds it.
*
* @param lockFile the path to the lock file
* @return true if the lock is held by another process, false otherwise
*/
public static boolean isLocked(Path lockFile) {
Objects.requireNonNull(lockFile, "lockFile must not be null");
if (!Files.exists(lockFile)) {
return false;
}
try (FileLock lock = tryAcquire(lockFile).orElse(null)) {
if (lock == null) {
return true; // Couldn't acquire, so it's locked
}
return false; // Acquired and released, so it wasn't locked
} catch (IOException e) {
LOG.debug("Error checking lock status: {}", e.getMessage());
return false; // Assume not locked on error
}
}
/**
* Returns the lock file path.
*
* @return the lock file path
*/
public Path getLockFile() {
return lockFile;
}
/**
* Releases the lock and closes the file channel.
*
* <p>The lock file is deleted after the lock is released.
*/
@Override
public void close() throws IOException {
try {
if (lock.isValid()) {
lock.release();
LOG.debug("Released lock: {}", lockFile);
}
} finally {
channel.close();
// Try to delete the lock file, but don't fail if it doesn't work
try {
Files.deleteIfExists(lockFile);
} catch (IOException e) {
LOG.debug("Could not delete lock file: {}", lockFile);
}
}
}
}
@@ -0,0 +1,67 @@
package com.samsonmedia.barn.state;
/**
* Represents the current state of a job in its lifecycle.
*/
public enum JobState {
/** Job is waiting to be executed. */
QUEUED,
/** Job is currently running. */
RUNNING,
/** Job completed successfully. */
SUCCEEDED,
/** Job failed to complete. */
FAILED,
/** Job was manually canceled. */
CANCELED;
/**
* Parses a job state from a string (case-insensitive).
*
* @param value the string value to parse
* @return the parsed JobState
* @throws IllegalArgumentException if the value is not a valid state
*/
public static JobState fromString(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Job state cannot be null or blank");
}
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid job state: '" + value + "'. Valid values are: queued, running, succeeded, failed, canceled");
}
}
/**
* Returns the lowercase string representation.
*
* @return the state name in lowercase
*/
public String toLowercase() {
return name().toLowerCase();
}
/**
* Checks if this is a terminal state (job is finished).
*
* @return true if the job is in a terminal state
*/
public boolean isTerminal() {
return this == SUCCEEDED || this == FAILED || this == CANCELED;
}
/**
* Checks if this is an active state (job is not finished).
*
* @return true if the job is active
*/
public boolean isActive() {
return !isTerminal();
}
}
@@ -0,0 +1,446 @@
package com.samsonmedia.barn.state;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
/**
* Manages state files for a job directory.
*
* <p>State files are plain-text files containing job metadata and lifecycle information.
* All writes are atomic to ensure consistency.
*/
public final class StateFiles {
/** State file name. */
public static final String STATE = "state";
/** Tag file name. */
public static final String TAG = "tag";
/** Created timestamp file name. */
public static final String CREATED_AT = "created_at";
/** Started timestamp file name. */
public static final String STARTED_AT = "started_at";
/** Finished timestamp file name. */
public static final String FINISHED_AT = "finished_at";
/** Exit code file name. */
public static final String EXIT_CODE = "exit_code";
/** Error message file name. */
public static final String ERROR = "error";
/** Process ID file name. */
public static final String PID = "pid";
/** Heartbeat timestamp file name. */
public static final String HEARTBEAT = "heartbeat";
/** Retry count file name. */
public static final String RETRY_COUNT = "retry_count";
/** Retry timestamp file name. */
public static final String RETRY_AT = "retry_at";
/** Retry history file name. */
public static final String RETRY_HISTORY = "retry_history";
/** Stage file name. */
public static final String STAGE = "stage";
private final Path jobDir;
/**
* Creates a StateFiles instance for the specified job directory.
*
* @param jobDir the job directory path
*/
public StateFiles(Path jobDir) {
this.jobDir = Objects.requireNonNull(jobDir, "jobDir must not be null");
}
/**
* Returns the job directory path.
*
* @return the job directory path
*/
public Path getJobDir() {
return jobDir;
}
// ========================================================================
// State
// ========================================================================
/**
* Writes the job state.
*
* @param state the job state
* @throws IOException if writing fails
*/
public void writeState(JobState state) throws IOException {
Objects.requireNonNull(state, "state must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(STATE), state.toLowercase());
}
/**
* Reads the job state.
*
* @return the job state, or empty if not found
* @throws IOException if reading fails
*/
public Optional<JobState> readState() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(STATE))
.map(JobState::fromString);
}
// ========================================================================
// Tag
// ========================================================================
/**
* Writes the job tag.
*
* @param tag the tag value
* @throws IOException if writing fails
*/
public void writeTag(String tag) throws IOException {
Objects.requireNonNull(tag, "tag must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(TAG), tag);
}
/**
* Reads the job tag.
*
* @return the tag, or empty if not found
* @throws IOException if reading fails
*/
public Optional<String> readTag() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(TAG));
}
// ========================================================================
// Timestamps
// ========================================================================
/**
* Writes the creation timestamp.
*
* @param timestamp the timestamp
* @throws IOException if writing fails
*/
public void writeCreatedAt(Instant timestamp) throws IOException {
writeTimestamp(CREATED_AT, timestamp);
}
/**
* Reads the creation timestamp.
*
* @return the timestamp, or empty if not found
* @throws IOException if reading fails
*/
public Optional<Instant> readCreatedAt() throws IOException {
return readTimestamp(CREATED_AT);
}
/**
* Writes the start timestamp.
*
* @param timestamp the timestamp
* @throws IOException if writing fails
*/
public void writeStartedAt(Instant timestamp) throws IOException {
writeTimestamp(STARTED_AT, timestamp);
}
/**
* Reads the start timestamp.
*
* @return the timestamp, or empty if not found
* @throws IOException if reading fails
*/
public Optional<Instant> readStartedAt() throws IOException {
return readTimestamp(STARTED_AT);
}
/**
* Writes the finished timestamp.
*
* @param timestamp the timestamp
* @throws IOException if writing fails
*/
public void writeFinishedAt(Instant timestamp) throws IOException {
writeTimestamp(FINISHED_AT, timestamp);
}
/**
* Reads the finished timestamp.
*
* @return the timestamp, or empty if not found
* @throws IOException if reading fails
*/
public Optional<Instant> readFinishedAt() throws IOException {
return readTimestamp(FINISHED_AT);
}
/**
* Writes the heartbeat timestamp.
*
* @param timestamp the timestamp
* @throws IOException if writing fails
*/
public void writeHeartbeat(Instant timestamp) throws IOException {
writeTimestamp(HEARTBEAT, timestamp);
}
/**
* Reads the heartbeat timestamp.
*
* @return the timestamp, or empty if not found
* @throws IOException if reading fails
*/
public Optional<Instant> readHeartbeat() throws IOException {
return readTimestamp(HEARTBEAT);
}
/**
* Writes the retry timestamp.
*
* @param timestamp the timestamp
* @throws IOException if writing fails
*/
public void writeRetryAt(Instant timestamp) throws IOException {
writeTimestamp(RETRY_AT, timestamp);
}
/**
* Reads the retry timestamp.
*
* @return the timestamp, or empty if not found
* @throws IOException if reading fails
*/
public Optional<Instant> readRetryAt() throws IOException {
return readTimestamp(RETRY_AT);
}
private void writeTimestamp(String filename, Instant timestamp) throws IOException {
Objects.requireNonNull(timestamp, "timestamp must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(filename), timestamp.toString());
}
private Optional<Instant> readTimestamp(String filename) throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(filename))
.flatMap(this::parseInstant);
}
private Optional<Instant> parseInstant(String value) {
try {
return Optional.of(Instant.parse(value));
} catch (DateTimeParseException e) {
return Optional.empty();
}
}
// ========================================================================
// Exit Code
// ========================================================================
/**
* Writes the exit code.
*
* @param code the exit code
* @throws IOException if writing fails
*/
public void writeExitCode(int code) throws IOException {
AtomicFiles.writeAtomically(jobDir.resolve(EXIT_CODE), String.valueOf(code));
}
/**
* Writes a symbolic exit code.
*
* @param symbolic the symbolic exit code (e.g., "orphaned_process")
* @throws IOException if writing fails
*/
public void writeExitCode(String symbolic) throws IOException {
Objects.requireNonNull(symbolic, "symbolic must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(EXIT_CODE), symbolic);
}
/**
* Reads the exit code as an integer.
*
* @return the exit code, or empty if not found or not an integer
* @throws IOException if reading fails
*/
public OptionalInt readExitCode() throws IOException {
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(EXIT_CODE));
if (value.isEmpty()) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(value.get()));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
/**
* Reads the exit code as a string (for symbolic codes).
*
* @return the exit code string, or empty if not found
* @throws IOException if reading fails
*/
public Optional<String> readExitCodeString() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(EXIT_CODE));
}
// ========================================================================
// Error
// ========================================================================
/**
* Writes the error message.
*
* @param error the error message
* @throws IOException if writing fails
*/
public void writeError(String error) throws IOException {
Objects.requireNonNull(error, "error must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(ERROR), error);
}
/**
* Reads the error message.
*
* @return the error message, or empty if not found
* @throws IOException if reading fails
*/
public Optional<String> readError() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(ERROR));
}
// ========================================================================
// PID
// ========================================================================
/**
* Writes the process ID.
*
* @param pid the process ID
* @throws IOException if writing fails
*/
public void writePid(long pid) throws IOException {
AtomicFiles.writeAtomically(jobDir.resolve(PID), String.valueOf(pid));
}
/**
* Reads the process ID.
*
* @return the process ID, or empty if not found
* @throws IOException if reading fails
*/
public OptionalLong readPid() throws IOException {
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(PID));
if (value.isEmpty()) {
return OptionalLong.empty();
}
try {
return OptionalLong.of(Long.parseLong(value.get()));
} catch (NumberFormatException e) {
return OptionalLong.empty();
}
}
// ========================================================================
// Retry Count
// ========================================================================
/**
* Writes the retry count.
*
* @param count the retry count
* @throws IOException if writing fails
*/
public void writeRetryCount(int count) throws IOException {
AtomicFiles.writeAtomically(jobDir.resolve(RETRY_COUNT), String.valueOf(count));
}
/**
* Reads the retry count.
*
* @return the retry count, or empty if not found
* @throws IOException if reading fails
*/
public OptionalInt readRetryCount() throws IOException {
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(RETRY_COUNT));
if (value.isEmpty()) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(value.get()));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
// ========================================================================
// Retry History
// ========================================================================
/**
* Appends an entry to the retry history.
*
* @param entry the entry to append
* @throws IOException if writing fails
*/
public void appendRetryHistory(String entry) throws IOException {
Objects.requireNonNull(entry, "entry must not be null");
Path historyFile = jobDir.resolve(RETRY_HISTORY);
String existing = AtomicFiles.readOrEmpty(historyFile);
String newContent = existing.isEmpty() ? entry : existing + "\n" + entry;
AtomicFiles.writeAtomically(historyFile, newContent);
}
/**
* Reads the retry history.
*
* @return the retry history, or empty if not found
* @throws IOException if reading fails
*/
public Optional<String> readRetryHistory() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(RETRY_HISTORY));
}
// ========================================================================
// Stage
// ========================================================================
/**
* Writes the current stage.
*
* @param stage the stage name
* @throws IOException if writing fails
*/
public void writeStage(String stage) throws IOException {
Objects.requireNonNull(stage, "stage must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(STAGE), stage);
}
/**
* Reads the current stage.
*
* @return the stage, or empty if not found
* @throws IOException if reading fails
*/
public Optional<String> readStage() throws IOException {
return AtomicFiles.readSafely(jobDir.resolve(STAGE));
}
}
@@ -0,0 +1,144 @@
package com.samsonmedia.barn.state;
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.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for AtomicFiles utility class.
*/
class AtomicFilesTest {
@TempDir
private Path tempDir;
@Test
void writeAtomically_withValidContent_shouldWriteFile() throws IOException {
Path target = tempDir.resolve("test.txt");
AtomicFiles.writeAtomically(target, "hello world");
assertThat(Files.readString(target)).isEqualTo("hello world");
}
@Test
void writeAtomically_withExistingFile_shouldOverwrite() throws IOException {
Path target = tempDir.resolve("test.txt");
Files.writeString(target, "old content");
AtomicFiles.writeAtomically(target, "new content");
assertThat(Files.readString(target)).isEqualTo("new content");
}
@Test
void writeAtomically_shouldNotLeaveTempFile() throws IOException {
Path target = tempDir.resolve("test.txt");
AtomicFiles.writeAtomically(target, "content");
assertThat(Files.exists(tempDir.resolve("test.txt.tmp"))).isFalse();
}
@Test
void writeAtomically_withNullTarget_shouldThrowException() {
assertThatThrownBy(() -> AtomicFiles.writeAtomically(null, "content"))
.isInstanceOf(NullPointerException.class);
}
@Test
void writeAtomically_withNullContent_shouldThrowException() {
Path target = tempDir.resolve("test.txt");
assertThatThrownBy(() -> AtomicFiles.writeAtomically(target, null))
.isInstanceOf(NullPointerException.class);
}
@Test
void readSafely_withExistingFile_shouldReturnContent() throws IOException {
Path file = tempDir.resolve("test.txt");
Files.writeString(file, " hello ");
Optional<String> result = AtomicFiles.readSafely(file);
assertThat(result).hasValue("hello");
}
@Test
void readSafely_withNonexistentFile_shouldReturnEmpty() throws IOException {
Path file = tempDir.resolve("nonexistent.txt");
Optional<String> result = AtomicFiles.readSafely(file);
assertThat(result).isEmpty();
}
@Test
void readSafely_withNullPath_shouldThrowException() {
assertThatThrownBy(() -> AtomicFiles.readSafely(null))
.isInstanceOf(NullPointerException.class);
}
@Test
void readOrEmpty_withExistingFile_shouldReturnContent() throws IOException {
Path file = tempDir.resolve("test.txt");
Files.writeString(file, "content");
String result = AtomicFiles.readOrEmpty(file);
assertThat(result).isEqualTo("content");
}
@Test
void readOrEmpty_withNonexistentFile_shouldReturnEmptyString() throws IOException {
Path file = tempDir.resolve("nonexistent.txt");
String result = AtomicFiles.readOrEmpty(file);
assertThat(result).isEmpty();
}
@Test
void deleteIfExists_withExistingFile_shouldDeleteAndReturnTrue() throws IOException {
Path file = tempDir.resolve("test.txt");
Files.writeString(file, "content");
boolean result = AtomicFiles.deleteIfExists(file);
assertThat(result).isTrue();
assertThat(Files.exists(file)).isFalse();
}
@Test
void deleteIfExists_withNonexistentFile_shouldReturnFalse() throws IOException {
Path file = tempDir.resolve("nonexistent.txt");
boolean result = AtomicFiles.deleteIfExists(file);
assertThat(result).isFalse();
}
@Test
void ensureParentDirectories_withNestedPath_shouldCreateDirectories() throws IOException {
Path nested = tempDir.resolve("a/b/c/file.txt");
AtomicFiles.ensureParentDirectories(nested);
assertThat(Files.exists(tempDir.resolve("a/b/c"))).isTrue();
}
@Test
void ensureParentDirectories_withExistingParent_shouldNotFail() throws IOException {
Path file = tempDir.resolve("file.txt");
AtomicFiles.ensureParentDirectories(file);
// No exception means success
}
}
@@ -0,0 +1,191 @@
package com.samsonmedia.barn.state;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for BarnDirectories.
*/
class BarnDirectoriesTest {
@TempDir
private Path tempDir;
private BarnDirectories directories;
@BeforeEach
void setUp() {
directories = new BarnDirectories(tempDir);
}
@Nested
class PathResolution {
@Test
void getBaseDir_shouldReturnBaseDir() {
assertThat(directories.getBaseDir()).isEqualTo(tempDir);
}
@Test
void getJobsDir_shouldReturnJobsSubdir() {
assertThat(directories.getJobsDir()).isEqualTo(tempDir.resolve("jobs"));
}
@Test
void getLocksDir_shouldReturnLocksSubdir() {
assertThat(directories.getLocksDir()).isEqualTo(tempDir.resolve("locks"));
}
@Test
void getLogsDir_shouldReturnLogsSubdir() {
assertThat(directories.getLogsDir()).isEqualTo(tempDir.resolve("logs"));
}
@Test
void getJobDir_shouldReturnJobSpecificDir() {
assertThat(directories.getJobDir("job-123"))
.isEqualTo(tempDir.resolve("jobs/job-123"));
}
@Test
void getJobWorkDir_shouldReturnWorkSubdir() {
assertThat(directories.getJobWorkDir("job-123"))
.isEqualTo(tempDir.resolve("jobs/job-123/work"));
}
@Test
void getJobInputDir_shouldReturnInputSubdir() {
assertThat(directories.getJobInputDir("job-123"))
.isEqualTo(tempDir.resolve("jobs/job-123/work/input"));
}
@Test
void getJobOutputDir_shouldReturnOutputSubdir() {
assertThat(directories.getJobOutputDir("job-123"))
.isEqualTo(tempDir.resolve("jobs/job-123/work/output"));
}
@Test
void getJobLogsDir_shouldReturnLogsSubdir() {
assertThat(directories.getJobLogsDir("job-123"))
.isEqualTo(tempDir.resolve("jobs/job-123/logs"));
}
@Test
void getJobLockFile_shouldReturnLockFile() {
assertThat(directories.getJobLockFile("job-123"))
.isEqualTo(tempDir.resolve("locks/job-job-123.lock"));
}
@Test
void getSchedulerLockFile_shouldReturnSchedulerLock() {
assertThat(directories.getSchedulerLockFile())
.isEqualTo(tempDir.resolve("locks/scheduler.lock"));
}
@Test
void getDaemonLogFile_shouldReturnBarnLog() {
assertThat(directories.getDaemonLogFile())
.isEqualTo(tempDir.resolve("logs/barn.log"));
}
}
@Nested
class DirectoryCreation {
@Test
void initialize_shouldCreateTopLevelDirectories() throws IOException {
directories.initialize();
assertThat(Files.isDirectory(directories.getJobsDir())).isTrue();
assertThat(Files.isDirectory(directories.getLocksDir())).isTrue();
assertThat(Files.isDirectory(directories.getLogsDir())).isTrue();
}
@Test
void initialize_withExistingDirectories_shouldNotFail() throws IOException {
directories.initialize();
directories.initialize(); // Second call should not fail
}
@Test
void createJobDirs_shouldCreateFullJobStructure() throws IOException {
directories.initialize();
directories.createJobDirs("job-123");
assertThat(Files.isDirectory(directories.getJobDir("job-123"))).isTrue();
assertThat(Files.isDirectory(directories.getJobInputDir("job-123"))).isTrue();
assertThat(Files.isDirectory(directories.getJobOutputDir("job-123"))).isTrue();
assertThat(Files.isDirectory(directories.getJobLogsDir("job-123"))).isTrue();
}
@Test
void createJobDirs_withNullJobId_shouldThrowException() {
assertThatThrownBy(() -> directories.createJobDirs(null))
.isInstanceOf(NullPointerException.class);
}
}
@Nested
class JobExistence {
@Test
void jobExists_withExistingJob_shouldReturnTrue() throws IOException {
directories.initialize();
directories.createJobDirs("job-123");
assertThat(directories.jobExists("job-123")).isTrue();
}
@Test
void jobExists_withNonexistentJob_shouldReturnFalse() throws IOException {
directories.initialize();
assertThat(directories.jobExists("nonexistent")).isFalse();
}
}
@Nested
class JobDeletion {
@Test
void deleteJobDir_shouldRemoveJobDirectory() throws IOException {
directories.initialize();
directories.createJobDirs("job-123");
Files.writeString(directories.getJobDir("job-123").resolve("state"), "running");
directories.deleteJobDir("job-123");
assertThat(directories.jobExists("job-123")).isFalse();
}
@Test
void deleteJobDir_withNonexistentJob_shouldNotFail() throws IOException {
directories.initialize();
directories.deleteJobDir("nonexistent"); // Should not throw
}
@Test
void deleteJobDir_withNullJobId_shouldThrowException() {
assertThatThrownBy(() -> directories.deleteJobDir(null))
.isInstanceOf(NullPointerException.class);
}
}
@Test
void constructor_withNullBaseDir_shouldThrowException() {
assertThatThrownBy(() -> new BarnDirectories(null))
.isInstanceOf(NullPointerException.class);
}
}
@@ -0,0 +1,135 @@
package com.samsonmedia.barn.state;
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.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for FileLock.
*/
class FileLockTest {
@TempDir
private Path tempDir;
@Test
void tryAcquire_shouldAcquireLock() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
Optional<FileLock> lock = FileLock.tryAcquire(lockFile);
assertThat(lock).isPresent();
lock.get().close();
}
@Test
void tryAcquire_shouldCreateLockFile() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
try (FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow()) {
assertThat(lock).isNotNull();
assertThat(Files.exists(lockFile)).isTrue();
}
}
@Test
void tryAcquire_withNestedPath_shouldCreateParentDirs() throws IOException {
Path lockFile = tempDir.resolve("a/b/c/test.lock");
try (FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow()) {
assertThat(lock).isNotNull();
assertThat(Files.exists(lockFile)).isTrue();
}
}
@Test
void tryAcquire_whenAlreadyLocked_shouldReturnEmpty() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
try (FileLock lock1 = FileLock.tryAcquire(lockFile).orElseThrow()) {
assertThat(lock1).isNotNull();
Optional<FileLock> lock2 = FileLock.tryAcquire(lockFile);
assertThat(lock2).isEmpty();
}
}
@Test
void close_shouldReleaseLock() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
FileLock lock1 = FileLock.tryAcquire(lockFile).orElseThrow();
lock1.close();
// Should be able to acquire lock again
Optional<FileLock> lock2 = FileLock.tryAcquire(lockFile);
assertThat(lock2).isPresent();
lock2.get().close();
}
@Test
void close_shouldDeleteLockFile() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow();
lock.close();
assertThat(Files.exists(lockFile)).isFalse();
}
@Test
void getLockFile_shouldReturnLockFilePath() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
try (FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow()) {
assertThat(lock.getLockFile()).isEqualTo(lockFile);
}
}
@Test
void isLocked_withLockedFile_shouldReturnTrue() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
try (FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow()) {
assertThat(lock).isNotNull();
assertThat(FileLock.isLocked(lockFile)).isTrue();
}
}
@Test
void isLocked_withUnlockedFile_shouldReturnFalse() throws IOException {
Path lockFile = tempDir.resolve("test.lock");
// Acquire and release
FileLock lock = FileLock.tryAcquire(lockFile).orElseThrow();
lock.close();
assertThat(FileLock.isLocked(lockFile)).isFalse();
}
@Test
void isLocked_withNonexistentFile_shouldReturnFalse() {
Path lockFile = tempDir.resolve("nonexistent.lock");
assertThat(FileLock.isLocked(lockFile)).isFalse();
}
@Test
void tryAcquire_withNullPath_shouldThrowException() {
assertThatThrownBy(() -> FileLock.tryAcquire(null))
.isInstanceOf(NullPointerException.class);
}
@Test
void isLocked_withNullPath_shouldThrowException() {
assertThatThrownBy(() -> FileLock.isLocked(null))
.isInstanceOf(NullPointerException.class);
}
}
@@ -0,0 +1,94 @@
package com.samsonmedia.barn.state;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
/**
* Tests for JobState enum.
*/
class JobStateTest {
@Test
void fromString_withValidLowercase_shouldReturnState() {
assertThat(JobState.fromString("queued")).isEqualTo(JobState.QUEUED);
assertThat(JobState.fromString("running")).isEqualTo(JobState.RUNNING);
assertThat(JobState.fromString("succeeded")).isEqualTo(JobState.SUCCEEDED);
assertThat(JobState.fromString("failed")).isEqualTo(JobState.FAILED);
assertThat(JobState.fromString("canceled")).isEqualTo(JobState.CANCELED);
}
@Test
void fromString_withValidUppercase_shouldReturnState() {
assertThat(JobState.fromString("QUEUED")).isEqualTo(JobState.QUEUED);
assertThat(JobState.fromString("RUNNING")).isEqualTo(JobState.RUNNING);
}
@Test
void fromString_withMixedCase_shouldReturnState() {
assertThat(JobState.fromString("Running")).isEqualTo(JobState.RUNNING);
assertThat(JobState.fromString("Failed")).isEqualTo(JobState.FAILED);
}
@Test
void fromString_withWhitespace_shouldTrimAndParse() {
assertThat(JobState.fromString(" queued ")).isEqualTo(JobState.QUEUED);
}
@Test
void fromString_withNull_shouldThrowException() {
assertThatThrownBy(() -> JobState.fromString(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null or blank");
}
@Test
void fromString_withBlank_shouldThrowException() {
assertThatThrownBy(() -> JobState.fromString(" "))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void fromString_withInvalidValue_shouldThrowException() {
assertThatThrownBy(() -> JobState.fromString("invalid"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid job state")
.hasMessageContaining("queued, running, succeeded, failed, canceled");
}
@Test
void toLowercase_shouldReturnLowercaseName() {
assertThat(JobState.QUEUED.toLowercase()).isEqualTo("queued");
assertThat(JobState.RUNNING.toLowercase()).isEqualTo("running");
assertThat(JobState.SUCCEEDED.toLowercase()).isEqualTo("succeeded");
assertThat(JobState.FAILED.toLowercase()).isEqualTo("failed");
assertThat(JobState.CANCELED.toLowercase()).isEqualTo("canceled");
}
@Test
void isTerminal_forTerminalStates_shouldReturnTrue() {
assertThat(JobState.SUCCEEDED.isTerminal()).isTrue();
assertThat(JobState.FAILED.isTerminal()).isTrue();
assertThat(JobState.CANCELED.isTerminal()).isTrue();
}
@Test
void isTerminal_forActiveStates_shouldReturnFalse() {
assertThat(JobState.QUEUED.isTerminal()).isFalse();
assertThat(JobState.RUNNING.isTerminal()).isFalse();
}
@Test
void isActive_forActiveStates_shouldReturnTrue() {
assertThat(JobState.QUEUED.isActive()).isTrue();
assertThat(JobState.RUNNING.isActive()).isTrue();
}
@Test
void isActive_forTerminalStates_shouldReturnFalse() {
assertThat(JobState.SUCCEEDED.isActive()).isFalse();
assertThat(JobState.FAILED.isActive()).isFalse();
assertThat(JobState.CANCELED.isActive()).isFalse();
}
}
@@ -0,0 +1,338 @@
package com.samsonmedia.barn.state;
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.time.Instant;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for StateFiles.
*/
class StateFilesTest {
@TempDir
private Path tempDir;
private Path jobDir;
private StateFiles stateFiles;
@BeforeEach
void setUp() throws IOException {
jobDir = tempDir.resolve("job-123");
Files.createDirectories(jobDir);
stateFiles = new StateFiles(jobDir);
}
@Nested
class StateTests {
@Test
void writeState_shouldWritePlainText() throws IOException {
stateFiles.writeState(JobState.RUNNING);
String content = Files.readString(jobDir.resolve("state"));
assertThat(content).isEqualTo("running");
}
@Test
void readState_withExistingFile_shouldReturnState() throws IOException {
Files.writeString(jobDir.resolve("state"), "queued");
Optional<JobState> result = stateFiles.readState();
assertThat(result).hasValue(JobState.QUEUED);
}
@Test
void readState_withNonexistentFile_shouldReturnEmpty() throws IOException {
Optional<JobState> result = stateFiles.readState();
assertThat(result).isEmpty();
}
@Test
void writeAndReadState_shouldRoundTrip() throws IOException {
stateFiles.writeState(JobState.FAILED);
Optional<JobState> result = stateFiles.readState();
assertThat(result).hasValue(JobState.FAILED);
}
}
@Nested
class TagTests {
@Test
void writeAndReadTag_shouldRoundTrip() throws IOException {
stateFiles.writeTag("my-tag");
Optional<String> result = stateFiles.readTag();
assertThat(result).hasValue("my-tag");
}
@Test
void readTag_withNonexistentFile_shouldReturnEmpty() throws IOException {
Optional<String> result = stateFiles.readTag();
assertThat(result).isEmpty();
}
}
@Nested
class TimestampTests {
private final Instant testTimestamp = Instant.parse("2026-01-21T18:42:10Z");
@Test
void writeCreatedAt_shouldWriteIso8601() throws IOException {
stateFiles.writeCreatedAt(testTimestamp);
String content = Files.readString(jobDir.resolve("created_at"));
assertThat(content).isEqualTo("2026-01-21T18:42:10Z");
}
@Test
void readCreatedAt_shouldParseIso8601() throws IOException {
Files.writeString(jobDir.resolve("created_at"), "2026-01-21T18:42:10Z");
Optional<Instant> result = stateFiles.readCreatedAt();
assertThat(result).hasValue(testTimestamp);
}
@Test
void writeAndReadStartedAt_shouldRoundTrip() throws IOException {
stateFiles.writeStartedAt(testTimestamp);
Optional<Instant> result = stateFiles.readStartedAt();
assertThat(result).hasValue(testTimestamp);
}
@Test
void writeAndReadFinishedAt_shouldRoundTrip() throws IOException {
stateFiles.writeFinishedAt(testTimestamp);
Optional<Instant> result = stateFiles.readFinishedAt();
assertThat(result).hasValue(testTimestamp);
}
@Test
void writeAndReadHeartbeat_shouldRoundTrip() throws IOException {
stateFiles.writeHeartbeat(testTimestamp);
Optional<Instant> result = stateFiles.readHeartbeat();
assertThat(result).hasValue(testTimestamp);
}
@Test
void writeAndReadRetryAt_shouldRoundTrip() throws IOException {
stateFiles.writeRetryAt(testTimestamp);
Optional<Instant> result = stateFiles.readRetryAt();
assertThat(result).hasValue(testTimestamp);
}
@Test
void readTimestamp_withInvalidFormat_shouldReturnEmpty() throws IOException {
Files.writeString(jobDir.resolve("created_at"), "not a timestamp");
Optional<Instant> result = stateFiles.readCreatedAt();
assertThat(result).isEmpty();
}
@Test
void readTimestamp_withNonexistentFile_shouldReturnEmpty() throws IOException {
Optional<Instant> result = stateFiles.readCreatedAt();
assertThat(result).isEmpty();
}
}
@Nested
class ExitCodeTests {
@Test
void writeExitCode_withInteger_shouldWrite() throws IOException {
stateFiles.writeExitCode(0);
String content = Files.readString(jobDir.resolve("exit_code"));
assertThat(content).isEqualTo("0");
}
@Test
void writeExitCode_withSymbolic_shouldWrite() throws IOException {
stateFiles.writeExitCode("orphaned_process");
String content = Files.readString(jobDir.resolve("exit_code"));
assertThat(content).isEqualTo("orphaned_process");
}
@Test
void readExitCode_withInteger_shouldReturnInt() throws IOException {
Files.writeString(jobDir.resolve("exit_code"), "42");
OptionalInt result = stateFiles.readExitCode();
assertThat(result).hasValue(42);
}
@Test
void readExitCode_withSymbolic_shouldReturnEmpty() throws IOException {
Files.writeString(jobDir.resolve("exit_code"), "orphaned_process");
OptionalInt result = stateFiles.readExitCode();
assertThat(result).isEmpty();
}
@Test
void readExitCodeString_withSymbolic_shouldReturnString() throws IOException {
Files.writeString(jobDir.resolve("exit_code"), "orphaned_process");
Optional<String> result = stateFiles.readExitCodeString();
assertThat(result).hasValue("orphaned_process");
}
}
@Nested
class ErrorTests {
@Test
void writeAndReadError_shouldRoundTrip() throws IOException {
stateFiles.writeError("Something went wrong");
Optional<String> result = stateFiles.readError();
assertThat(result).hasValue("Something went wrong");
}
@Test
void readError_withNonexistentFile_shouldReturnEmpty() throws IOException {
Optional<String> result = stateFiles.readError();
assertThat(result).isEmpty();
}
}
@Nested
class PidTests {
@Test
void writeAndReadPid_shouldRoundTrip() throws IOException {
stateFiles.writePid(12345L);
OptionalLong result = stateFiles.readPid();
assertThat(result).hasValue(12345L);
}
@Test
void readPid_withNonNumeric_shouldReturnEmpty() throws IOException {
Files.writeString(jobDir.resolve("pid"), "not a number");
OptionalLong result = stateFiles.readPid();
assertThat(result).isEmpty();
}
@Test
void readPid_withNonexistentFile_shouldReturnEmpty() throws IOException {
OptionalLong result = stateFiles.readPid();
assertThat(result).isEmpty();
}
}
@Nested
class RetryCountTests {
@Test
void writeAndReadRetryCount_shouldRoundTrip() throws IOException {
stateFiles.writeRetryCount(2);
OptionalInt result = stateFiles.readRetryCount();
assertThat(result).hasValue(2);
}
@Test
void readRetryCount_withNonexistentFile_shouldReturnEmpty() throws IOException {
OptionalInt result = stateFiles.readRetryCount();
assertThat(result).isEmpty();
}
}
@Nested
class RetryHistoryTests {
@Test
void appendRetryHistory_shouldAddEntry() throws IOException {
stateFiles.appendRetryHistory("Attempt 1: exit_code=1");
Optional<String> result = stateFiles.readRetryHistory();
assertThat(result).hasValue("Attempt 1: exit_code=1");
}
@Test
void appendRetryHistory_shouldAppendToExisting() throws IOException {
stateFiles.appendRetryHistory("Attempt 1: exit_code=1");
stateFiles.appendRetryHistory("Attempt 2: exit_code=2");
Optional<String> result = stateFiles.readRetryHistory();
assertThat(result).hasValue("Attempt 1: exit_code=1\nAttempt 2: exit_code=2");
}
}
@Nested
class StageTests {
@Test
void writeAndReadStage_shouldRoundTrip() throws IOException {
stateFiles.writeStage("transcode");
Optional<String> result = stateFiles.readStage();
assertThat(result).hasValue("transcode");
}
@Test
void readStage_withNonexistentFile_shouldReturnEmpty() throws IOException {
Optional<String> result = stateFiles.readStage();
assertThat(result).isEmpty();
}
}
@Test
void getJobDir_shouldReturnJobDir() {
assertThat(stateFiles.getJobDir()).isEqualTo(jobDir);
}
@Test
void constructor_withNullJobDir_shouldThrowException() {
assertThatThrownBy(() -> new StateFiles(null))
.isInstanceOf(NullPointerException.class);
}
}