From c6e26bbedb326aabe227f42edb59fd1199418f56 Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Wed, 21 Jan 2026 13:15:19 +0000 Subject: [PATCH] feat(jobs): implement job model and state machine (#4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add core job management infrastructure: - Job record with lifecycle methods (createQueued, withStarted, withCompleted, withRetry, withCanceled) - JobIdGenerator for unique job identifiers (job-XXXXXXXX format) - JobManifest for immutable job configuration with retry settings - JobStateMachine for validating state transitions - JobRepository for filesystem persistence using atomic operations State transitions: QUEUED → RUNNING → SUCCEEDED/FAILED/CANCELED Failed jobs can transition back to QUEUED for retry. Includes 87 tests covering all components with comprehensive edge case coverage. Co-Authored-By: Claude Opus 4.5 --- .../java/com/samsonmedia/barn/jobs/Job.java | 185 +++++++++ .../samsonmedia/barn/jobs/JobIdGenerator.java | 61 +++ .../samsonmedia/barn/jobs/JobManifest.java | 126 +++++++ .../samsonmedia/barn/jobs/JobRepository.java | 355 ++++++++++++++++++ .../barn/jobs/JobStateMachine.java | 114 ++++++ .../samsonmedia/barn/state/StateFiles.java | 8 +- .../barn/jobs/JobIdGeneratorTest.java | 88 +++++ .../barn/jobs/JobManifestTest.java | 152 ++++++++ .../barn/jobs/JobRepositoryTest.java | 306 +++++++++++++++ .../barn/jobs/JobStateMachineTest.java | 203 ++++++++++ .../com/samsonmedia/barn/jobs/JobTest.java | 234 ++++++++++++ 11 files changed, 1830 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/samsonmedia/barn/jobs/Job.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/JobIdGenerator.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/JobManifest.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/JobRepository.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/JobStateMachine.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/JobIdGeneratorTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/JobStateMachineTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/JobTest.java diff --git a/src/main/java/com/samsonmedia/barn/jobs/Job.java b/src/main/java/com/samsonmedia/barn/jobs/Job.java new file mode 100644 index 0000000..8a85027 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/Job.java @@ -0,0 +1,185 @@ +package com.samsonmedia.barn.jobs; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; + +import com.samsonmedia.barn.state.JobState; + +/** + * Represents a job in the Barn system. + * + *

A job is an external command to be executed by the daemon. This record + * captures the current state and metadata of a job. + * + * @param id unique identifier (e.g., "job-9f83c") + * @param state current lifecycle state + * @param command command and arguments to execute + * @param tag optional user-defined tag + * @param createdAt when the job was created + * @param startedAt when execution started (null if not started) + * @param finishedAt when execution finished (null if not finished) + * @param exitCode process exit code (null if not finished) + * @param error error message (null if no error) + * @param pid OS process ID (null if not started) + * @param heartbeat last liveness check timestamp + * @param retryCount current retry attempt (0-based) + * @param retryAt when to retry (null if not scheduled for retry) + */ +public record Job( + String id, + JobState state, + List command, + String tag, + Instant createdAt, + Instant startedAt, + Instant finishedAt, + Integer exitCode, + String error, + Long pid, + Instant heartbeat, + int retryCount, + Instant retryAt +) { + + /** + * Creates a Job with validation. + */ + public Job { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(state, "state must not be null"); + Objects.requireNonNull(command, "command must not be null"); + Objects.requireNonNull(createdAt, "createdAt must not be null"); + if (id.isBlank()) { + throw new IllegalArgumentException("id must not be blank"); + } + if (command.isEmpty()) { + throw new IllegalArgumentException("command must not be empty"); + } + if (retryCount < 0) { + throw new IllegalArgumentException("retryCount must be non-negative"); + } + command = List.copyOf(command); + } + + /** + * Creates a new queued job with minimal required fields. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @return a new Job in QUEUED state + */ + public static Job createQueued(String id, List command, String tag) { + return new Job( + id, + JobState.QUEUED, + command, + tag, + Instant.now(), + null, // startedAt + null, // finishedAt + null, // exitCode + null, // error + null, // pid + null, // heartbeat + 0, // retryCount + null // retryAt + ); + } + + /** + * Creates a copy of this job with a new state. + * + * @param newState the new state + * @return a new Job with the updated state + */ + public Job withState(JobState newState) { + return new Job(id, newState, command, tag, createdAt, startedAt, finishedAt, + exitCode, error, pid, heartbeat, retryCount, retryAt); + } + + /** + * Creates a copy of this job marked as started. + * + * @param processId the OS process ID + * @return a new Job in RUNNING state + */ + public Job withStarted(long processId) { + Instant now = Instant.now(); + return new Job(id, JobState.RUNNING, command, tag, createdAt, now, finishedAt, + exitCode, error, processId, now, retryCount, retryAt); + } + + /** + * Creates a copy of this job marked as completed. + * + * @param code the exit code + * @param errorMessage optional error message (may be null) + * @return a new Job in terminal state + */ + public Job withCompleted(int code, String errorMessage) { + JobState newState = (code == 0) ? JobState.SUCCEEDED : JobState.FAILED; + return new Job(id, newState, command, tag, createdAt, startedAt, Instant.now(), + code, errorMessage, pid, heartbeat, retryCount, retryAt); + } + + /** + * Creates a copy of this job with updated heartbeat. + * + * @param timestamp the heartbeat timestamp + * @return a new Job with updated heartbeat + */ + public Job withHeartbeat(Instant timestamp) { + return new Job(id, state, command, tag, createdAt, startedAt, finishedAt, + exitCode, error, pid, timestamp, retryCount, retryAt); + } + + /** + * Creates a copy of this job scheduled for retry. + * + * @param retryTimestamp when to retry + * @return a new Job in QUEUED state with incremented retry count + */ + public Job withRetry(Instant retryTimestamp) { + return new Job(id, JobState.QUEUED, command, tag, createdAt, null, null, + null, null, null, null, retryCount + 1, retryTimestamp); + } + + /** + * Creates a copy of this job marked as canceled. + * + * @return a new Job in CANCELED state + */ + public Job withCanceled() { + return new Job(id, JobState.CANCELED, command, tag, createdAt, startedAt, Instant.now(), + exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt); + } + + /** + * Checks if this job is in a terminal state. + * + * @return true if the job is finished + */ + public boolean isTerminal() { + return state.isTerminal(); + } + + /** + * Checks if this job is actively running. + * + * @return true if the job is running + */ + public boolean isRunning() { + return state == JobState.RUNNING; + } + + /** + * Checks if this job is waiting to be executed. + * + * @return true if the job is queued + */ + public boolean isQueued() { + return state == JobState.QUEUED; + } +} diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobIdGenerator.java b/src/main/java/com/samsonmedia/barn/jobs/JobIdGenerator.java new file mode 100644 index 0000000..cf112fa --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/JobIdGenerator.java @@ -0,0 +1,61 @@ +package com.samsonmedia.barn.jobs; + +import java.security.SecureRandom; + +/** + * Generates unique job identifiers. + * + *

Job IDs follow the format: "job-" followed by 8 random hexadecimal characters. + * For example: "job-9f83c012" + */ +public final class JobIdGenerator { + + private static final String PREFIX = "job-"; + private static final int HEX_LENGTH = 8; + private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); + private static final SecureRandom RANDOM = new SecureRandom(); + + private JobIdGenerator() { + // Utility class - prevent instantiation + } + + /** + * Generates a new unique job ID. + * + * @return a new job ID in the format "job-XXXXX" + */ + public static String generate() { + StringBuilder sb = new StringBuilder(PREFIX.length() + HEX_LENGTH); + sb.append(PREFIX); + for (int i = 0; i < HEX_LENGTH; i++) { + sb.append(HEX_CHARS[RANDOM.nextInt(HEX_CHARS.length)]); + } + return sb.toString(); + } + + /** + * Validates that a string is a valid job ID format. + * + * @param id the ID to validate + * @return true if the ID matches the expected format + */ + public static boolean isValid(String id) { + if (id == null || id.length() != PREFIX.length() + HEX_LENGTH) { + return false; + } + if (!id.startsWith(PREFIX)) { + return false; + } + String hex = id.substring(PREFIX.length()); + for (char c : hex.toCharArray()) { + if (!isHexChar(c)) { + return false; + } + } + return true; + } + + private static boolean isHexChar(char c) { + return c >= '0' && c <= '9' || c >= 'a' && c <= 'f'; + } +} diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java b/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java new file mode 100644 index 0000000..8352618 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java @@ -0,0 +1,126 @@ +package com.samsonmedia.barn.jobs; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; + +import com.samsonmedia.barn.config.JobsConfig; + +/** + * Immutable job definition stored as manifest.json. + * + *

The manifest is written once when a job is created and never modified. + * It contains the job's command and retry configuration. + * + * @param id unique job identifier + * @param command command and arguments to execute + * @param tag optional user-defined tag + * @param createdAt when the job was created + * @param maxRetries maximum number of retry attempts + * @param retryDelaySeconds initial delay before first retry + * @param retryBackoffMultiplier multiplier for exponential backoff + */ +public record JobManifest( + String id, + List command, + String tag, + Instant createdAt, + int maxRetries, + int retryDelaySeconds, + double retryBackoffMultiplier +) { + + /** + * Creates a JobManifest with validation. + */ + public JobManifest { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(command, "command must not be null"); + Objects.requireNonNull(createdAt, "createdAt must not be null"); + if (id.isBlank()) { + throw new IllegalArgumentException("id must not be blank"); + } + if (command.isEmpty()) { + throw new IllegalArgumentException("command must not be empty"); + } + 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"); + } + command = List.copyOf(command); + } + + /** + * Creates a JobManifest with default retry configuration from JobsConfig. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @param config the jobs configuration for defaults + * @return a new JobManifest + */ + public static JobManifest create(String id, List command, String tag, JobsConfig config) { + Objects.requireNonNull(config, "config must not be null"); + return new JobManifest( + id, + command, + tag, + Instant.now(), + config.maxRetries(), + config.retryDelaySeconds(), + config.retryBackoffMultiplier() + ); + } + + /** + * Creates a JobManifest with custom retry configuration. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @param maxRetries maximum retry attempts + * @param retryDelaySeconds initial retry delay + * @param retryBackoffMultiplier backoff multiplier + * @return a new JobManifest + */ + public static JobManifest create(String id, List command, String tag, + int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier) { + return new JobManifest( + id, + command, + tag, + Instant.now(), + maxRetries, + retryDelaySeconds, + retryBackoffMultiplier + ); + } + + /** + * Calculates the delay for a specific retry attempt using exponential backoff. + * + * @param retryCount the current retry count (0-based) + * @return the delay in seconds + */ + public int calculateRetryDelay(int retryCount) { + if (retryCount < 0) { + throw new IllegalArgumentException("retryCount must be non-negative"); + } + return (int) (retryDelaySeconds * Math.pow(retryBackoffMultiplier, retryCount)); + } + + /** + * Checks if another retry is allowed. + * + * @param currentRetryCount the current retry count + * @return true if retries are available + */ + public boolean canRetry(int currentRetryCount) { + return currentRetryCount < maxRetries; + } +} diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java b/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java new file mode 100644 index 0000000..5e08986 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java @@ -0,0 +1,355 @@ +package com.samsonmedia.barn.jobs; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.samsonmedia.barn.config.JobsConfig; +import com.samsonmedia.barn.state.AtomicFiles; +import com.samsonmedia.barn.state.BarnDirectories; +import com.samsonmedia.barn.state.JobState; +import com.samsonmedia.barn.state.StateFiles; + +/** + * Repository for persisting jobs to the filesystem. + * + *

Jobs are stored in directories under the jobs directory, with state + * files and a manifest.json containing the immutable job definition. + */ +public class JobRepository { + + private static final Logger LOG = LoggerFactory.getLogger(JobRepository.class); + private static final String MANIFEST_FILE = "manifest.json"; + + private final BarnDirectories dirs; + private final ObjectMapper objectMapper; + + /** + * Creates a JobRepository with the specified directories. + * + * @param dirs the Barn directories manager + */ + public JobRepository(BarnDirectories dirs) { + this.dirs = Objects.requireNonNull(dirs, "dirs must not be null"); + this.objectMapper = createObjectMapper(); + } + + private static ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + return mapper; + } + + /** + * Creates a new job with the given command and configuration. + * + * @param command the command to execute + * @param tag optional user tag (may be null) + * @param config the jobs configuration for defaults + * @return the created Job + * @throws IOException if creation fails + */ + public Job create(List command, String tag, JobsConfig config) throws IOException { + Objects.requireNonNull(command, "command must not be null"); + Objects.requireNonNull(config, "config must not be null"); + + String id = JobIdGenerator.generate(); + JobManifest manifest = JobManifest.create(id, command, tag, config); + + // Create directories + dirs.createJobDirs(id); + + // Write manifest + Path manifestPath = dirs.getJobDir(id).resolve(MANIFEST_FILE); + String manifestJson = objectMapper.writeValueAsString(manifest); + AtomicFiles.writeAtomically(manifestPath, manifestJson); + + // Write initial state files + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + stateFiles.writeState(JobState.QUEUED); + stateFiles.writeCreatedAt(manifest.createdAt()); + if (tag != null) { + stateFiles.writeTag(tag); + } + stateFiles.writeRetryCount(0); + + LOG.info("Created job: {}", id); + return Job.createQueued(id, command, tag); + } + + /** + * Finds a job by its ID. + * + * @param id the job ID + * @return the job if found, or empty + * @throws IOException if reading fails + */ + public Optional findById(String id) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + if (!dirs.jobExists(id)) { + return Optional.empty(); + } + + return Optional.of(loadJob(id)); + } + + /** + * Lists all jobs. + * + * @return list of all jobs + * @throws IOException if reading fails + */ + public List findAll() throws IOException { + Path jobsDir = dirs.getJobsDir(); + if (!Files.exists(jobsDir)) { + return List.of(); + } + + List jobs = new ArrayList<>(); + try (Stream stream = Files.list(jobsDir)) { + for (Path jobPath : stream.toList()) { + if (Files.isDirectory(jobPath)) { + String id = jobPath.getFileName().toString(); + try { + jobs.add(loadJob(id)); + } catch (IOException e) { + LOG.warn("Failed to load job {}: {}", id, e.getMessage()); + } + } + } + } + return jobs; + } + + /** + * Finds all jobs in a specific state. + * + * @param state the state to filter by + * @return list of jobs in the specified state + * @throws IOException if reading fails + */ + public List findByState(JobState state) throws IOException { + Objects.requireNonNull(state, "state must not be null"); + return findAll().stream() + .filter(job -> job.state() == state) + .toList(); + } + + /** + * Updates the state of a job. + * + * @param id the job ID + * @param newState the new state + * @throws IOException if update fails + * @throws IllegalStateException if the transition is invalid + */ + public void updateState(String id, JobState newState) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(newState, "newState must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + Optional currentState = stateFiles.readState(); + + if (currentState.isPresent()) { + JobStateMachine.validateTransition(currentState.get(), newState); + } + + stateFiles.writeState(newState); + LOG.debug("Updated job {} state to {}", id, newState); + } + + /** + * Marks a job as started. + * + * @param id the job ID + * @param pid the OS process ID + * @throws IOException if update fails + */ + public void markStarted(String id, long pid) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + Instant now = Instant.now(); + + updateState(id, JobState.RUNNING); + stateFiles.writeStartedAt(now); + stateFiles.writePid(pid); + stateFiles.writeHeartbeat(now); + + LOG.info("Job {} started with PID {}", id, pid); + } + + /** + * Updates the heartbeat for a running job. + * + * @param id the job ID + * @param timestamp the heartbeat timestamp + * @throws IOException if update fails + */ + public void updateHeartbeat(String id, Instant timestamp) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(timestamp, "timestamp must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + stateFiles.writeHeartbeat(timestamp); + } + + /** + * Marks a job as completed. + * + * @param id the job ID + * @param exitCode the process exit code + * @param error optional error message (may be null) + * @throws IOException if update fails + */ + public void markCompleted(String id, int exitCode, String error) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + JobState newState = (exitCode == 0) ? JobState.SUCCEEDED : JobState.FAILED; + + updateState(id, newState); + stateFiles.writeFinishedAt(Instant.now()); + stateFiles.writeExitCode(exitCode); + if (error != null) { + stateFiles.writeError(error); + } + + LOG.info("Job {} completed with exit code {}", id, exitCode); + } + + /** + * Marks a job as failed with a symbolic exit code. + * + * @param id the job ID + * @param symbolicCode the symbolic exit code (e.g., "orphaned_process") + * @param error the error message + * @throws IOException if update fails + */ + public void markFailed(String id, String symbolicCode, String error) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(symbolicCode, "symbolicCode must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + + updateState(id, JobState.FAILED); + stateFiles.writeFinishedAt(Instant.now()); + stateFiles.writeExitCode(symbolicCode); + if (error != null) { + stateFiles.writeError(error); + } + + LOG.info("Job {} failed: {}", id, symbolicCode); + } + + /** + * Schedules a job for retry. + * + * @param id the job ID + * @param retryAt when to retry + * @throws IOException if update fails + */ + public void scheduleRetry(String id, Instant retryAt) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + Objects.requireNonNull(retryAt, "retryAt must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + + // Increment retry count + int currentCount = stateFiles.readRetryCount().orElse(0); + stateFiles.writeRetryCount(currentCount + 1); + stateFiles.writeRetryAt(retryAt); + + // Transition back to queued + updateState(id, JobState.QUEUED); + + // Clear runtime state + stateFiles.writeStartedAt(null); + stateFiles.writeHeartbeat(null); + + LOG.info("Job {} scheduled for retry at {} (attempt {})", id, retryAt, currentCount + 1); + } + + /** + * Marks a job as canceled. + * + * @param id the job ID + * @throws IOException if update fails + */ + public void markCanceled(String id) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + StateFiles stateFiles = new StateFiles(dirs.getJobDir(id)); + + updateState(id, JobState.CANCELED); + stateFiles.writeFinishedAt(Instant.now()); + stateFiles.writeError("Job was canceled"); + + LOG.info("Job {} canceled", id); + } + + /** + * Deletes a job and its directory. + * + * @param id the job ID + * @throws IOException if deletion fails + */ + public void delete(String id) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + dirs.deleteJobDir(id); + LOG.info("Deleted job: {}", id); + } + + /** + * Loads the manifest for a job. + * + * @param id the job ID + * @return the job manifest + * @throws IOException if loading fails + */ + public JobManifest loadManifest(String id) throws IOException { + Objects.requireNonNull(id, "id must not be null"); + + Path manifestPath = dirs.getJobDir(id).resolve(MANIFEST_FILE); + String json = Files.readString(manifestPath); + return objectMapper.readValue(json, JobManifest.class); + } + + private Job loadJob(String id) throws IOException { + Path jobDir = dirs.getJobDir(id); + StateFiles stateFiles = new StateFiles(jobDir); + JobManifest manifest = loadManifest(id); + + return new Job( + id, + stateFiles.readState().orElse(JobState.QUEUED), + manifest.command(), + stateFiles.readTag().orElse(null), + stateFiles.readCreatedAt().orElse(manifest.createdAt()), + stateFiles.readStartedAt().orElse(null), + stateFiles.readFinishedAt().orElse(null), + stateFiles.readExitCode().isPresent() ? stateFiles.readExitCode().getAsInt() : null, + stateFiles.readError().orElse(null), + stateFiles.readPid().isPresent() ? stateFiles.readPid().getAsLong() : null, + stateFiles.readHeartbeat().orElse(null), + stateFiles.readRetryCount().orElse(0), + stateFiles.readRetryAt().orElse(null) + ); + } +} diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobStateMachine.java b/src/main/java/com/samsonmedia/barn/jobs/JobStateMachine.java new file mode 100644 index 0000000..9a01fc8 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/JobStateMachine.java @@ -0,0 +1,114 @@ +package com.samsonmedia.barn.jobs; + +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import com.samsonmedia.barn.state.JobState; + +/** + * Enforces valid state transitions for jobs. + * + *

Valid transitions: + *

+ */ +public final class JobStateMachine { + + private static final Map> VALID_TRANSITIONS = Map.of( + JobState.QUEUED, Set.of(JobState.RUNNING, JobState.CANCELED), + JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED), + JobState.FAILED, Set.of(JobState.QUEUED), // For retry + JobState.SUCCEEDED, Set.of(), + JobState.CANCELED, Set.of() + ); + + private JobStateMachine() { + // Utility class - prevent instantiation + } + + /** + * Validates that a state transition is allowed. + * + * @param from the current state + * @param to the target state + * @throws IllegalStateException if the transition is not valid + */ + public static void validateTransition(JobState from, JobState to) { + Objects.requireNonNull(from, "from state must not be null"); + Objects.requireNonNull(to, "to state must not be null"); + + Set validTargets = VALID_TRANSITIONS.get(from); + if (!validTargets.contains(to)) { + throw new IllegalStateException( + "Invalid state transition: " + from + " -> " + to); + } + } + + /** + * Checks if a state transition is valid. + * + * @param from the current state + * @param to the target state + * @return true if the transition is valid + */ + public static boolean isValidTransition(JobState from, JobState to) { + if (from == null || to == null) { + return false; + } + return VALID_TRANSITIONS.get(from).contains(to); + } + + /** + * Gets the valid target states for a given state. + * + * @param state the current state + * @return the set of valid target states + */ + public static Set getValidTransitions(JobState state) { + Objects.requireNonNull(state, "state must not be null"); + return VALID_TRANSITIONS.get(state); + } + + /** + * Record representing a state transition event. + * + * @param from the previous state + * @param to the new state + * @param timestamp when the transition occurred + * @param reason optional reason for the transition + */ + public record Transition( + JobState from, + JobState to, + Instant timestamp, + String reason + ) { + /** + * Creates a Transition with validation. + */ + public Transition { + Objects.requireNonNull(from, "from must not be null"); + Objects.requireNonNull(to, "to must not be null"); + Objects.requireNonNull(timestamp, "timestamp must not be null"); + } + + /** + * Creates a Transition with the current timestamp. + * + * @param from the previous state + * @param to the new state + * @param reason optional reason + * @return a new Transition + */ + public static Transition now(JobState from, JobState to, String reason) { + return new Transition(from, to, Instant.now(), reason); + } + } +} diff --git a/src/main/java/com/samsonmedia/barn/state/StateFiles.java b/src/main/java/com/samsonmedia/barn/state/StateFiles.java index 1d493e0..f115a2a 100644 --- a/src/main/java/com/samsonmedia/barn/state/StateFiles.java +++ b/src/main/java/com/samsonmedia/barn/state/StateFiles.java @@ -232,8 +232,12 @@ public final class StateFiles { } private void writeTimestamp(String filename, Instant timestamp) throws IOException { - Objects.requireNonNull(timestamp, "timestamp must not be null"); - AtomicFiles.writeAtomically(jobDir.resolve(filename), timestamp.toString()); + Path file = jobDir.resolve(filename); + if (timestamp == null) { + AtomicFiles.deleteIfExists(file); + } else { + AtomicFiles.writeAtomically(file, timestamp.toString()); + } } private Optional readTimestamp(String filename) throws IOException { diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobIdGeneratorTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobIdGeneratorTest.java new file mode 100644 index 0000000..d328eb7 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/JobIdGeneratorTest.java @@ -0,0 +1,88 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +/** + * Tests for JobIdGenerator. + */ +class JobIdGeneratorTest { + + @Test + void generate_shouldReturnIdWithCorrectPrefix() { + String id = JobIdGenerator.generate(); + + assertThat(id).startsWith("job-"); + } + + @Test + void generate_shouldReturnIdWithCorrectLength() { + String id = JobIdGenerator.generate(); + + assertThat(id).hasSize(12); // "job-" (4) + 8 hex chars + } + + @Test + void generate_shouldReturnIdWithHexSuffix() { + String id = JobIdGenerator.generate(); + String suffix = id.substring(4); + + assertThat(suffix).matches("[0-9a-f]{8}"); + } + + @Test + void generate_shouldProduceUniqueIds() { + Set ids = new HashSet<>(); + + for (int i = 0; i < 1000; i++) { + ids.add(JobIdGenerator.generate()); + } + + assertThat(ids).hasSize(1000); + } + + @Test + void isValid_withValidId_shouldReturnTrue() { + assertThat(JobIdGenerator.isValid("job-12345678")).isTrue(); + assertThat(JobIdGenerator.isValid("job-abcdef01")).isTrue(); + assertThat(JobIdGenerator.isValid("job-9f83c012")).isTrue(); + } + + @Test + void isValid_withNull_shouldReturnFalse() { + assertThat(JobIdGenerator.isValid(null)).isFalse(); + } + + @Test + void isValid_withWrongPrefix_shouldReturnFalse() { + assertThat(JobIdGenerator.isValid("task-12345678")).isFalse(); + assertThat(JobIdGenerator.isValid("12345678")).isFalse(); + } + + @Test + void isValid_withWrongLength_shouldReturnFalse() { + assertThat(JobIdGenerator.isValid("job-1234567")).isFalse(); + assertThat(JobIdGenerator.isValid("job-123456789")).isFalse(); + } + + @Test + void isValid_withInvalidHexChars_shouldReturnFalse() { + assertThat(JobIdGenerator.isValid("job-ABCDEF01")).isFalse(); + assertThat(JobIdGenerator.isValid("job-ghijklmn")).isFalse(); + assertThat(JobIdGenerator.isValid("job-12-45678")).isFalse(); + } + + @Test + void generate_shouldPassOwnValidation() { + for (int i = 0; i < 100; i++) { + String id = JobIdGenerator.generate(); + assertThat(JobIdGenerator.isValid(id)) + .as("Generated ID '%s' should be valid", id) + .isTrue(); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java new file mode 100644 index 0000000..531ad48 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java @@ -0,0 +1,152 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.samsonmedia.barn.config.JobsConfig; + +/** + * Tests for JobManifest record. + */ +class JobManifestTest { + + @Test + void constructor_withValidValues_shouldCreateManifest() { + Instant now = Instant.now(); + JobManifest manifest = new JobManifest( + "job-12345", + List.of("echo", "hello"), + "test-tag", + now, + 3, 30, 2.0 + ); + + assertThat(manifest.id()).isEqualTo("job-12345"); + assertThat(manifest.command()).containsExactly("echo", "hello"); + assertThat(manifest.tag()).isEqualTo("test-tag"); + assertThat(manifest.createdAt()).isEqualTo(now); + assertThat(manifest.maxRetries()).isEqualTo(3); + assertThat(manifest.retryDelaySeconds()).isEqualTo(30); + assertThat(manifest.retryBackoffMultiplier()).isEqualTo(2.0); + } + + @Test + void constructor_withNullId_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + null, List.of("echo"), null, Instant.now(), 3, 30, 2.0)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("id"); + } + + @Test + void constructor_withBlankId_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + " ", List.of("echo"), null, Instant.now(), 3, 30, 2.0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("blank"); + } + + @Test + void constructor_withEmptyCommand_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + "job-12345", List.of(), null, Instant.now(), 3, 30, 2.0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty"); + } + + @Test + void constructor_withNegativeMaxRetries_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxRetries"); + } + + @Test + void constructor_withNegativeRetryDelay_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("retryDelaySeconds"); + } + + @Test + void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() { + assertThatThrownBy(() -> new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("retryBackoffMultiplier"); + } + + @Test + void create_withConfig_shouldUseConfigDefaults() { + JobsConfig config = JobsConfig.withDefaults(); + + JobManifest manifest = JobManifest.create("job-12345", List.of("echo"), "tag", config); + + assertThat(manifest.maxRetries()).isEqualTo(config.maxRetries()); + assertThat(manifest.retryDelaySeconds()).isEqualTo(config.retryDelaySeconds()); + assertThat(manifest.retryBackoffMultiplier()).isEqualTo(config.retryBackoffMultiplier()); + } + + @Test + void create_withCustomValues_shouldUseCustomValues() { + JobManifest manifest = JobManifest.create( + "job-12345", List.of("echo"), "tag", 5, 60, 3.0); + + assertThat(manifest.maxRetries()).isEqualTo(5); + assertThat(manifest.retryDelaySeconds()).isEqualTo(60); + assertThat(manifest.retryBackoffMultiplier()).isEqualTo(3.0); + } + + @Test + void calculateRetryDelay_shouldUseExponentialBackoff() { + JobManifest manifest = new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + + assertThat(manifest.calculateRetryDelay(0)).isEqualTo(30); // 30 * 2^0 + assertThat(manifest.calculateRetryDelay(1)).isEqualTo(60); // 30 * 2^1 + assertThat(manifest.calculateRetryDelay(2)).isEqualTo(120); // 30 * 2^2 + } + + @Test + void calculateRetryDelay_withNegativeCount_shouldThrowException() { + JobManifest manifest = new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + + assertThatThrownBy(() -> manifest.calculateRetryDelay(-1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void canRetry_withRetriesAvailable_shouldReturnTrue() { + JobManifest manifest = new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + + assertThat(manifest.canRetry(0)).isTrue(); + assertThat(manifest.canRetry(1)).isTrue(); + assertThat(manifest.canRetry(2)).isTrue(); + } + + @Test + void canRetry_withNoRetriesLeft_shouldReturnFalse() { + JobManifest manifest = new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + + assertThat(manifest.canRetry(3)).isFalse(); + assertThat(manifest.canRetry(4)).isFalse(); + } + + @Test + void canRetry_withZeroMaxRetries_shouldAlwaysReturnFalse() { + JobManifest manifest = new JobManifest( + "job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0); + + assertThat(manifest.canRetry(0)).isFalse(); + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java new file mode 100644 index 0000000..87ecb7b --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java @@ -0,0 +1,306 @@ +package com.samsonmedia.barn.jobs; + +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.List; +import java.util.Optional; + +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; + +import com.samsonmedia.barn.config.JobsConfig; +import com.samsonmedia.barn.state.BarnDirectories; +import com.samsonmedia.barn.state.JobState; + +/** + * Tests for JobRepository. + */ +class JobRepositoryTest { + + @TempDir + private Path tempDir; + + private BarnDirectories dirs; + private JobRepository repository; + private JobsConfig config; + + @BeforeEach + void setUp() throws IOException { + dirs = new BarnDirectories(tempDir); + dirs.initialize(); + repository = new JobRepository(dirs); + config = JobsConfig.withDefaults(); + } + + @Nested + class Create { + + @Test + void create_shouldCreateJobDirectory() throws IOException { + Job job = repository.create(List.of("echo", "hello"), "test-tag", config); + + assertThat(Files.isDirectory(dirs.getJobDir(job.id()))).isTrue(); + } + + @Test + void create_shouldWriteManifest() throws IOException { + Job job = repository.create(List.of("echo", "hello"), "test-tag", config); + + Path manifestPath = dirs.getJobDir(job.id()).resolve("manifest.json"); + assertThat(Files.exists(manifestPath)).isTrue(); + String content = Files.readString(manifestPath); + assertThat(content).contains("echo"); + assertThat(content).contains("hello"); + } + + @Test + void create_shouldWriteInitialState() throws IOException { + Job job = repository.create(List.of("echo", "hello"), "test-tag", config); + + Path statePath = dirs.getJobDir(job.id()).resolve("state"); + assertThat(Files.readString(statePath).trim()).isEqualTo("queued"); + } + + @Test + void create_shouldReturnQueuedJob() throws IOException { + Job job = repository.create(List.of("echo", "hello"), "test-tag", config); + + assertThat(job.state()).isEqualTo(JobState.QUEUED); + assertThat(job.command()).containsExactly("echo", "hello"); + assertThat(job.tag()).isEqualTo("test-tag"); + } + + @Test + void create_withNullTag_shouldSucceed() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + assertThat(job.tag()).isNull(); + } + } + + @Nested + class FindById { + + @Test + void findById_withExistingJob_shouldReturnJob() throws IOException { + Job created = repository.create(List.of("echo"), "tag", config); + + Optional found = repository.findById(created.id()); + + assertThat(found).isPresent(); + assertThat(found.get().id()).isEqualTo(created.id()); + assertThat(found.get().command()).isEqualTo(created.command()); + } + + @Test + void findById_withNonexistentJob_shouldReturnEmpty() throws IOException { + Optional found = repository.findById("job-nonexistent"); + + assertThat(found).isEmpty(); + } + } + + @Nested + class FindAll { + + @Test + void findAll_withNoJobs_shouldReturnEmpty() throws IOException { + List jobs = repository.findAll(); + + assertThat(jobs).isEmpty(); + } + + @Test + void findAll_withMultipleJobs_shouldReturnAll() throws IOException { + repository.create(List.of("echo", "1"), "tag1", config); + repository.create(List.of("echo", "2"), "tag2", config); + repository.create(List.of("echo", "3"), "tag3", config); + + List jobs = repository.findAll(); + + assertThat(jobs).hasSize(3); + } + } + + @Nested + class FindByState { + + @Test + void findByState_shouldFilterByState() throws IOException { + Job job1 = repository.create(List.of("echo", "1"), null, config); + Job job2 = repository.create(List.of("echo", "2"), null, config); + repository.markStarted(job1.id(), 12345L); + + List queued = repository.findByState(JobState.QUEUED); + List running = repository.findByState(JobState.RUNNING); + + assertThat(queued).hasSize(1); + assertThat(queued.get(0).id()).isEqualTo(job2.id()); + assertThat(running).hasSize(1); + assertThat(running.get(0).id()).isEqualTo(job1.id()); + } + } + + @Nested + class MarkStarted { + + @Test + void markStarted_shouldUpdateState() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + repository.markStarted(job.id(), 12345L); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.RUNNING); + assertThat(updated.pid()).isEqualTo(12345L); + assertThat(updated.startedAt()).isNotNull(); + assertThat(updated.heartbeat()).isNotNull(); + } + } + + @Nested + class UpdateHeartbeat { + + @Test + void updateHeartbeat_shouldWriteTimestamp() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + repository.markStarted(job.id(), 12345L); + Instant newHeartbeat = Instant.now().plusSeconds(60); + + repository.updateHeartbeat(job.id(), newHeartbeat); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.heartbeat()).isEqualTo(newHeartbeat); + } + } + + @Nested + class MarkCompleted { + + @Test + void markCompleted_withZeroExitCode_shouldSetSucceeded() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + repository.markStarted(job.id(), 12345L); + + repository.markCompleted(job.id(), 0, null); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.SUCCEEDED); + assertThat(updated.exitCode()).isZero(); + assertThat(updated.finishedAt()).isNotNull(); + } + + @Test + void markCompleted_withNonZeroExitCode_shouldSetFailed() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + repository.markStarted(job.id(), 12345L); + + repository.markCompleted(job.id(), 1, "Process failed"); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.FAILED); + assertThat(updated.exitCode()).isEqualTo(1); + assertThat(updated.error()).isEqualTo("Process failed"); + } + } + + @Nested + class MarkFailed { + + @Test + void markFailed_withSymbolicCode_shouldSetFailed() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + repository.markStarted(job.id(), 12345L); + + repository.markFailed(job.id(), "orphaned_process", "Process was orphaned"); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.FAILED); + assertThat(updated.error()).isEqualTo("Process was orphaned"); + } + } + + @Nested + class ScheduleRetry { + + @Test + void scheduleRetry_shouldIncrementCountAndResetState() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + repository.markStarted(job.id(), 12345L); + repository.markCompleted(job.id(), 1, "Failed"); + Instant retryAt = Instant.now().plusSeconds(30); + + repository.scheduleRetry(job.id(), retryAt); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.QUEUED); + assertThat(updated.retryCount()).isEqualTo(1); + assertThat(updated.retryAt()).isEqualTo(retryAt); + } + } + + @Nested + class MarkCanceled { + + @Test + void markCanceled_shouldSetCanceledState() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + repository.markCanceled(job.id()); + + Job updated = repository.findById(job.id()).orElseThrow(); + assertThat(updated.state()).isEqualTo(JobState.CANCELED); + assertThat(updated.finishedAt()).isNotNull(); + } + } + + @Nested + class Delete { + + @Test + void delete_shouldRemoveJobDirectory() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + repository.delete(job.id()); + + assertThat(Files.exists(dirs.getJobDir(job.id()))).isFalse(); + assertThat(repository.findById(job.id())).isEmpty(); + } + } + + @Nested + class LoadManifest { + + @Test + void loadManifest_shouldReturnManifest() throws IOException { + Job job = repository.create(List.of("echo", "test"), "my-tag", config); + + JobManifest manifest = repository.loadManifest(job.id()); + + assertThat(manifest.id()).isEqualTo(job.id()); + assertThat(manifest.command()).containsExactly("echo", "test"); + assertThat(manifest.tag()).isEqualTo("my-tag"); + assertThat(manifest.maxRetries()).isEqualTo(config.maxRetries()); + } + } + + @Nested + class StateTransitionValidation { + + @Test + void updateState_withInvalidTransition_shouldThrowException() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + assertThatThrownBy(() -> repository.updateState(job.id(), JobState.SUCCEEDED)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Invalid state transition"); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobStateMachineTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobStateMachineTest.java new file mode 100644 index 0000000..dc3f936 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/JobStateMachineTest.java @@ -0,0 +1,203 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import com.samsonmedia.barn.state.JobState; + +/** + * Tests for JobStateMachine. + */ +class JobStateMachineTest { + + @Nested + class ValidateTransition { + + @Test + void queued_toRunning_shouldBeValid() { + JobStateMachine.validateTransition(JobState.QUEUED, JobState.RUNNING); + // No exception means valid + } + + @Test + void queued_toCanceled_shouldBeValid() { + JobStateMachine.validateTransition(JobState.QUEUED, JobState.CANCELED); + } + + @Test + void running_toSucceeded_shouldBeValid() { + JobStateMachine.validateTransition(JobState.RUNNING, JobState.SUCCEEDED); + } + + @Test + void running_toFailed_shouldBeValid() { + JobStateMachine.validateTransition(JobState.RUNNING, JobState.FAILED); + } + + @Test + void running_toCanceled_shouldBeValid() { + JobStateMachine.validateTransition(JobState.RUNNING, JobState.CANCELED); + } + + @Test + void failed_toQueued_shouldBeValid() { + JobStateMachine.validateTransition(JobState.FAILED, JobState.QUEUED); + } + + @Test + void queued_toSucceeded_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.QUEUED, JobState.SUCCEEDED)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Invalid state transition") + .hasMessageContaining("QUEUED") + .hasMessageContaining("SUCCEEDED"); + } + + @Test + void queued_toFailed_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.QUEUED, JobState.FAILED)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void succeeded_toAny_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.SUCCEEDED, JobState.QUEUED)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.SUCCEEDED, JobState.RUNNING)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void canceled_toAny_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.CANCELED, JobState.QUEUED)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.CANCELED, JobState.RUNNING)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void withNullFrom_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(null, JobState.RUNNING)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void withNullTo_shouldThrowException() { + assertThatThrownBy(() -> + JobStateMachine.validateTransition(JobState.QUEUED, null)) + .isInstanceOf(NullPointerException.class); + } + } + + @Nested + class IsValidTransition { + + @Test + void validTransitions_shouldReturnTrue() { + assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.RUNNING)).isTrue(); + assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.CANCELED)).isTrue(); + assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.SUCCEEDED)).isTrue(); + assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.FAILED)).isTrue(); + assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.CANCELED)).isTrue(); + assertThat(JobStateMachine.isValidTransition(JobState.FAILED, JobState.QUEUED)).isTrue(); + } + + @Test + void invalidTransitions_shouldReturnFalse() { + assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.SUCCEEDED)).isFalse(); + assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.FAILED)).isFalse(); + assertThat(JobStateMachine.isValidTransition(JobState.SUCCEEDED, JobState.QUEUED)).isFalse(); + assertThat(JobStateMachine.isValidTransition(JobState.CANCELED, JobState.RUNNING)).isFalse(); + } + + @Test + void withNull_shouldReturnFalse() { + assertThat(JobStateMachine.isValidTransition(null, JobState.RUNNING)).isFalse(); + assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, null)).isFalse(); + } + } + + @Nested + class GetValidTransitions { + + @Test + void forQueued_shouldReturnRunningAndCanceled() { + assertThat(JobStateMachine.getValidTransitions(JobState.QUEUED)) + .containsExactlyInAnyOrder(JobState.RUNNING, JobState.CANCELED); + } + + @Test + void forRunning_shouldReturnSucceededFailedCanceled() { + assertThat(JobStateMachine.getValidTransitions(JobState.RUNNING)) + .containsExactlyInAnyOrder(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED); + } + + @Test + void forFailed_shouldReturnQueued() { + assertThat(JobStateMachine.getValidTransitions(JobState.FAILED)) + .containsExactly(JobState.QUEUED); + } + + @Test + void forSucceeded_shouldReturnEmpty() { + assertThat(JobStateMachine.getValidTransitions(JobState.SUCCEEDED)).isEmpty(); + } + + @Test + void forCanceled_shouldReturnEmpty() { + assertThat(JobStateMachine.getValidTransitions(JobState.CANCELED)).isEmpty(); + } + + @Test + void withNull_shouldThrowException() { + assertThatThrownBy(() -> JobStateMachine.getValidTransitions(null)) + .isInstanceOf(NullPointerException.class); + } + } + + @Nested + class TransitionRecord { + + @Test + void constructor_shouldCreateTransition() { + Instant now = Instant.now(); + JobStateMachine.Transition transition = new JobStateMachine.Transition( + JobState.QUEUED, JobState.RUNNING, now, "Starting execution"); + + assertThat(transition.from()).isEqualTo(JobState.QUEUED); + assertThat(transition.to()).isEqualTo(JobState.RUNNING); + assertThat(transition.timestamp()).isEqualTo(now); + assertThat(transition.reason()).isEqualTo("Starting execution"); + } + + @Test + void constructor_withNullFrom_shouldThrowException() { + assertThatThrownBy(() -> + new JobStateMachine.Transition(null, JobState.RUNNING, Instant.now(), null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void now_shouldCreateWithCurrentTimestamp() { + JobStateMachine.Transition transition = JobStateMachine.Transition.now( + JobState.QUEUED, JobState.RUNNING, "Test"); + + assertThat(transition.from()).isEqualTo(JobState.QUEUED); + assertThat(transition.to()).isEqualTo(JobState.RUNNING); + assertThat(transition.timestamp()).isNotNull(); + assertThat(transition.reason()).isEqualTo("Test"); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobTest.java new file mode 100644 index 0000000..d36af99 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/JobTest.java @@ -0,0 +1,234 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.samsonmedia.barn.state.JobState; + +/** + * Tests for Job record. + */ +class JobTest { + + @Test + void constructor_withValidValues_shouldCreateJob() { + Job job = new Job( + "job-12345", + JobState.QUEUED, + List.of("echo", "hello"), + "test-tag", + Instant.now(), + null, null, null, null, null, null, 0, null + ); + + assertThat(job.id()).isEqualTo("job-12345"); + assertThat(job.state()).isEqualTo(JobState.QUEUED); + assertThat(job.command()).containsExactly("echo", "hello"); + assertThat(job.tag()).isEqualTo("test-tag"); + } + + @Test + void constructor_withNullId_shouldThrowException() { + assertThatThrownBy(() -> new Job( + null, JobState.QUEUED, List.of("echo"), null, + Instant.now(), null, null, null, null, null, null, 0, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("id"); + } + + @Test + void constructor_withBlankId_shouldThrowException() { + assertThatThrownBy(() -> new Job( + " ", JobState.QUEUED, List.of("echo"), null, + Instant.now(), null, null, null, null, null, null, 0, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("blank"); + } + + @Test + void constructor_withNullState_shouldThrowException() { + assertThatThrownBy(() -> new Job( + "job-12345", null, List.of("echo"), null, + Instant.now(), null, null, null, null, null, null, 0, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("state"); + } + + @Test + void constructor_withEmptyCommand_shouldThrowException() { + assertThatThrownBy(() -> new Job( + "job-12345", JobState.QUEUED, List.of(), null, + Instant.now(), null, null, null, null, null, null, 0, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty"); + } + + @Test + void constructor_withNegativeRetryCount_shouldThrowException() { + assertThatThrownBy(() -> new Job( + "job-12345", JobState.QUEUED, List.of("echo"), null, + Instant.now(), null, null, null, null, null, null, -1, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("retryCount"); + } + + @Test + void constructor_shouldMakeDefensiveCopyOfCommand() { + List command = new java.util.ArrayList<>(); + command.add("echo"); + Job job = Job.createQueued("job-12345", command, null); + command.add("modified"); + + assertThat(job.command()).containsExactly("echo"); + } + + @Test + void createQueued_shouldCreateQueuedJob() { + Job job = Job.createQueued("job-12345", List.of("echo", "test"), "my-tag"); + + assertThat(job.id()).isEqualTo("job-12345"); + assertThat(job.state()).isEqualTo(JobState.QUEUED); + assertThat(job.command()).containsExactly("echo", "test"); + assertThat(job.tag()).isEqualTo("my-tag"); + assertThat(job.createdAt()).isNotNull(); + assertThat(job.startedAt()).isNull(); + assertThat(job.finishedAt()).isNull(); + assertThat(job.exitCode()).isNull(); + assertThat(job.retryCount()).isZero(); + } + + @Test + void withState_shouldCreateCopyWithNewState() { + Job original = Job.createQueued("job-12345", List.of("echo"), null); + + Job updated = original.withState(JobState.RUNNING); + + assertThat(updated.state()).isEqualTo(JobState.RUNNING); + assertThat(updated.id()).isEqualTo(original.id()); + assertThat(updated.command()).isEqualTo(original.command()); + assertThat(original.state()).isEqualTo(JobState.QUEUED); // Original unchanged + } + + @Test + void withStarted_shouldSetRunningStateAndPid() { + Job original = Job.createQueued("job-12345", List.of("echo"), null); + + Job started = original.withStarted(12345L); + + assertThat(started.state()).isEqualTo(JobState.RUNNING); + assertThat(started.pid()).isEqualTo(12345L); + assertThat(started.startedAt()).isNotNull(); + assertThat(started.heartbeat()).isNotNull(); + } + + @Test + void withCompleted_withZeroExitCode_shouldSetSucceeded() { + Job running = Job.createQueued("job-12345", List.of("echo"), null) + .withStarted(12345L); + + Job completed = running.withCompleted(0, null); + + assertThat(completed.state()).isEqualTo(JobState.SUCCEEDED); + assertThat(completed.exitCode()).isZero(); + assertThat(completed.finishedAt()).isNotNull(); + } + + @Test + void withCompleted_withNonZeroExitCode_shouldSetFailed() { + Job running = Job.createQueued("job-12345", List.of("echo"), null) + .withStarted(12345L); + + Job completed = running.withCompleted(1, "Process failed"); + + assertThat(completed.state()).isEqualTo(JobState.FAILED); + assertThat(completed.exitCode()).isEqualTo(1); + assertThat(completed.error()).isEqualTo("Process failed"); + } + + @Test + void withHeartbeat_shouldUpdateHeartbeat() { + Job running = Job.createQueued("job-12345", List.of("echo"), null) + .withStarted(12345L); + Instant newHeartbeat = Instant.now().plusSeconds(60); + + Job updated = running.withHeartbeat(newHeartbeat); + + assertThat(updated.heartbeat()).isEqualTo(newHeartbeat); + } + + @Test + void withRetry_shouldIncrementRetryCountAndResetState() { + Job failed = Job.createQueued("job-12345", List.of("echo"), null) + .withStarted(12345L) + .withCompleted(1, "Failed"); + Instant retryAt = Instant.now().plusSeconds(30); + + Job retrying = failed.withRetry(retryAt); + + assertThat(retrying.state()).isEqualTo(JobState.QUEUED); + assertThat(retrying.retryCount()).isEqualTo(1); + assertThat(retrying.retryAt()).isEqualTo(retryAt); + assertThat(retrying.startedAt()).isNull(); + assertThat(retrying.finishedAt()).isNull(); + } + + @Test + void withCanceled_shouldSetCanceledState() { + Job running = Job.createQueued("job-12345", List.of("echo"), null) + .withStarted(12345L); + + Job canceled = running.withCanceled(); + + assertThat(canceled.state()).isEqualTo(JobState.CANCELED); + assertThat(canceled.error()).contains("canceled"); + assertThat(canceled.finishedAt()).isNotNull(); + } + + @Test + void isTerminal_forTerminalStates_shouldReturnTrue() { + Job succeeded = Job.createQueued("job-1", List.of("echo"), null) + .withStarted(1L).withCompleted(0, null); + Job failed = Job.createQueued("job-2", List.of("echo"), null) + .withStarted(1L).withCompleted(1, null); + Job canceled = Job.createQueued("job-3", List.of("echo"), null) + .withCanceled(); + + assertThat(succeeded.isTerminal()).isTrue(); + assertThat(failed.isTerminal()).isTrue(); + assertThat(canceled.isTerminal()).isTrue(); + } + + @Test + void isTerminal_forActiveStates_shouldReturnFalse() { + Job queued = Job.createQueued("job-1", List.of("echo"), null); + Job running = queued.withStarted(1L); + + assertThat(queued.isTerminal()).isFalse(); + assertThat(running.isTerminal()).isFalse(); + } + + @Test + void isRunning_shouldReturnTrueOnlyForRunning() { + Job queued = Job.createQueued("job-1", List.of("echo"), null); + Job running = queued.withStarted(1L); + Job completed = running.withCompleted(0, null); + + assertThat(queued.isRunning()).isFalse(); + assertThat(running.isRunning()).isTrue(); + assertThat(completed.isRunning()).isFalse(); + } + + @Test + void isQueued_shouldReturnTrueOnlyForQueued() { + Job queued = Job.createQueued("job-1", List.of("echo"), null); + Job running = queued.withStarted(1L); + + assertThat(queued.isQueued()).isTrue(); + assertThat(running.isQueued()).isFalse(); + } +}